2017-07-25 49 views
1

我正在制作工具列表。将数据对象从父项传递到子项

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

在子组件,我得到这个错误:

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

哪里...是工具数据对象的任何属性,例如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查找解决方案。我在这里错过了什么?

+0

声明道具子组件引用它在你的子组件的模板,该子组件supossed接受。 –

+0

我知道我可以做到这一点。但有什么办法可以传递完整的数据对象吗? – Lazlo

+1

是的这是可能的,你可以将'$ data'存储在属性''中,但是不确定这是个好主意。 –

回答

5

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

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> 
相关问题