我是 vue.js 的新手,我尝试将值传递给子组件。
HTML
<div id="example">
<my-component v-bind:data="parentData"></my-component>
</div>
JS
Vue.component('my-component', {
props: ['data'],
template: '<div>Parent component with data: {{ data.value }}!<div is="my-component-child" v-bind:data="childData"></div></div>'
});
Vue.component('my-component-child', {
props: ['data'],
template: '<div>Child component with data: {{ data.value }} </div>'
});
new Vue({
el: '#example',
data: {
parentData: {
value: 'hello parent!'
},
childData: {
value: 'hello child!'
}
}
});
https://jsfiddle.net/v9osont9/2/
我遇到了这个错误:
[Vue warn]: Property or method "childData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in )
[Vue warn]: Error in render function: (found in )
TypeError: Cannot read property 'value' of undefined
执行此操作的正确方法是什么?
最佳答案
当你打电话时
<my-component v-bind:data="parentData"></my-component>
您仅将 parentData
传递给您的父组件,而 childData
超出范围。
您需要将您的 childData
嵌套在您的 parentData
中:
new Vue({
el: '#example',
data: {
parentData: {
value: 'hello parent!',
childData: {
value: 'hello child!'
}
}
}
});
然后像这样把它传给你的 child :
<div is="my-component-child" v-bind:data="data.childData">
关于vue.js - vue.js 如何将数据传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47331308/