Pass data object from parent to child component

北战南征 提交于 2019-12-24 00:58:04

问题


I'm making a list of tools.

I'm trying to pass the full tool data object from the parent component (the tool list) to each child component (the tool items), using single file templates.

In the child component, I get this error:

Property or method "..." is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Where ... is any property of the tool data object, for example title or description.

Here's my setup:

Tools.vue (parent):

<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 (child):

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

<script>
    export default {}
</script>

It should be simple, but I'm unable to find the solution with my google-fu. What am I missing here?


回答1:


If you want to pass the entire tool object, first declare the property.

export default {
  props: ["tool"]
}

Then, pass it using your v-for.

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

You can reference it in your child component's template using

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


来源:https://stackoverflow.com/questions/45313990/pass-data-object-from-parent-to-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!