将数据对象从父项传递给子组件(Pass data object from parent to child component)

编程入门 行业动态 更新时间:2024-10-11 01:19:14
将数据对象从父项传递给子组件(Pass data object from parent to child component)

我正在制作一个工具列表。

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

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

属性或方法“...”没有在实例上定义,但在渲染过程中被引用。 确保在数据选项中声明反应数据属性。

其中...是工具数据对象的任何属性,例如title或description 。

这是我的设置:

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

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

它应该很简单,但我无法通过google-fu找到解决方案。 我在这里错过了什么?

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?

最满意答案

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

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>

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>

更多推荐

本文发布于:2023-07-27 08:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   对象   数据   Pass   data

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!