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

时间:2017-01-16 03:07:09

标签: 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>

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>

1 个答案:

答案 0 :(得分: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>

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

所以我发布了documentation

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