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

koj*_*jot 3 vue.js vue-component vuejs2

我是 vue.js 的新手,我尝试将值传递给子组件。

HTML

<div id="example">
   <my-component v-bind:data="parentData"></my-component>
</div>
Run Code Online (Sandbox Code Playgroud)

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!'
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/v9osont9/2/

我有这个错误:

[Vue 警告]:属性或方法“childData”未在实例上定义,但在渲染期间被引用。确保在数据选项中声明反应数据属性。(在发现 )

[Vue 警告]:渲染函数出错:(在 中找到)

类型错误:无法读取未定义的属性“值”

这样做的正确方法是什么?

cef*_*ari 5

你打电话时

<my-component v-bind:data="parentData"></my-component> 
Run Code Online (Sandbox Code Playgroud)

您仅将 传递parentData给您的父组件并childData超出范围。

你需要将你的嵌套childData在你的parentData

new Vue({
    el: '#example',
    data: {
        parentData: {
            value: 'hello parent!',
            childData: {
                value: 'hello child!'
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

并像这样将其传递给您的孩子:

<div is="my-component-child" v-bind:data="data.childData"> 
Run Code Online (Sandbox Code Playgroud)