我已经开始使用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>
答案 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.
}
})