如何在 vue.js 中将数据传递给子组件
2017-11-16
5055
我是 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
正确的做法是什么?
1个回答
当您调用
<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!'
}
}
}
});
并将其传递给您的子组件,如下所示:
<div is="my-component-child" v-bind:data="data.childData">
ceferrari
2017-11-16