Vuejs - 使用props将数据从父级传递给子级

Ste*_*hev 1 javascript vue.js

我已经开始玩了,Vue但在尝试使用时将数据传递给组件时遇到了问题props.在下面的代码this.myData(在Hello.vue)中是undefined出于某种原因

App.vue

<script>
import Hello from './components/Hello'

export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  } ...
 </script>
Run Code Online (Sandbox Code Playgroud)

Hello.vue

<script>
export default {
  name: 'hello',
  props: ['myData'],
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
  mounted: function() {
       console.log(this.myData)
   }
} ...
</script>
Run Code Online (Sandbox Code Playgroud)

Amr*_*pal 5

你需要在父类中使用子组件,所以:

// inside app.vue
<template>
  <hello :myData='myData'></hello> // I believe this is your objective
</template> //:myData is binding the property from the components data field, without using it, you will get myData as `string` in the child component.

<script>
  export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  }
</script>
Run Code Online (Sandbox Code Playgroud)

OP要求一种方法将道具传递给孩子而不在模板中渲染孩子.

所以我发布了文档的链接

Vue.component('hello', {
  render: function (createElement) {
    return createElement(
      <tag-names>
    )
  },
  props: {
    myData: parentComponent.myData // you need to give the parent components' data here.
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 是的,这种方式有效。所以数据总是应该通过模板?如果我只想传递数据而不实际渲染它(例如一些配置设置)怎么办? (2认同)
  • @AmreshVenugopal 当父级和子级都是 Vue 单文件组件时,如何在子级中设置 `parentComponent.myData`? (2认同)