vue.js - vue.js 如何将数据传递给子组件

标签 vue.js vuejs2 vue-component

我是 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/

相关文章:

vue.js - Vue 实例位于另一个 Vue 实例中

javascript - 如何使用 vue.js 获取所选选项的索引

vuejs2 - 使用 VueJS 进行表格分页

vue.js - 更新的生命周期事件 : act using watcher after dom update on specific element only

css - 如何检查应用了哪些类的组件?

javascript - Vue.js 组件模型更新

javascript - 在 VUE.js 中如何将此表达式 **newCat = $event.target.value** 从 **input** 传输到 **methods**?

laravel - VueJS 和 laravel 验证数组

vue.js - 如何禁用 Vue 转换组等待浏览器选项卡被选择?

javascript - Vue.js 在组件之间传递数据