【问题标题】:How to pass data to child component in vue.js如何将数据传递给 vue.js 中的子组件
【发布时间】:2018-04-30 02:07:59
【问题描述】:

我是 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 警告]:属性或方法“childData”未在实例上定义,但在渲染期间被引用。确保在 data 选项中声明反应数据属性。 (见于)

[Vue 警告]:渲染函数出错: (见于)

TypeError: 无法读取未定义的属性“值”

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

【问题讨论】:

  • 请注意data 是一个不好的属性名称,因为在 Vue 组件中data 表示数据模型,它是一种保留字。

标签: vue.js vuejs2 vue-component


【解决方案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"> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2023-03-04
    • 2020-06-21
    • 2016-04-04
    • 2020-11-01
    • 2019-02-14
    • 2016-12-13
    • 2018-08-12
    相关资源
    最近更新 更多