【问题标题】:Pass data object from parent to child component将数据对象从父组件传递到子组件
【发布时间】:2018-01-01 00:15:57
【问题描述】:

我正在制作工具列表。

我正在尝试使用单个文件模板将完整的工具数据对象从父组件(工具列表)传递到每个子组件(工具项)。

在子组件中,我收到此错误:

属性或方法“...”未在实例上定义,但在渲染期间被引用。确保在 data 选项中声明响应式数据属性。

其中... 是工具数据对象的任何属性,例如titledescription

这是我的设置:

Tools.vue(父级):

<template>
    <main id="tools">
        <tool v-for="tool in tools" :data="tool" :key="tool.id"></tool>
    </main>
</template>

<script>
    import Tool from './Tool.vue'

    let test = {
        id: 1,
        title: 'Title',
        description: 'Description'
    };

    export default {
        data() {
            return {
                tools: [
                    test
                ]
            }
        },

        components: {'tool': Tool}
    }
</script>

Tool.vue(子):

<template>
    <div class="tool">
        <div class="title">{{ title }}</div>
        <div class="description">{{ description }}</div>
    </div>
</template>

<script>
    export default {}
</script>

应该很简单,但我无法用我的 google-fu 找到解决方案。我在这里想念什么?

【问题讨论】:

  • 在子组件中声明 props,该子组件应该接受。
  • 我知道我可以做到。但是有什么方法可以传递完整的数据对象吗?
  • 是的,有可能,您可以将$data 存储在&lt;tool :random-prop="$data"&gt;&lt;/tool&gt; 属性中,但不确定这是不是个好主意。

标签: vue.js vuejs2 vue-component


【解决方案1】:

如果要传递整个工具对象,首先声明属性。

export default {
  props: ["tool"]
}

然后,使用您的 v-for 传递它。

<tool v-for="tool in tools" :tool="tool" :key="tool.id"></tool>

您可以在子组件的模板中使用

<div class="title">{{ tool.title }}</div>
<div class="description">{{ tool.description }}</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2019-02-27
    • 2017-04-20
    相关资源
    最近更新 更多