我有一个数组 sheets
在数据中初始化,按下按钮时有一个项目推送给它
data() {
return {
sheets: []
};
}
在 html 中,我试图为这个数组中的每个元素添加一个 Card
组件,并将数据作为 prop 传递,但是没有呈现任何组件,也没有错误消息.我还尝试将 v-for
直接放在组件上,但结果相同
<div id="sheets">
<template v-for="c in sheets">
<Card :info="c"/>
</template>
</div>
同时,如果我这样做,它会正确显示数组中的所有数据,所以我不明白这里出了什么问题
<div id="sheets">
<template v-for="c in sheets">
<span>{{c}}</span>
</template>
</div>
--
解决方案 在我的组件中,来自 prop 的数据在 created() 函数中被操作,它在我在 mounted() 函数中执行此操作之后起作用
最佳答案
确保您正确完成了以下事情:
- 导入了您的
Card
组件 - 传递和访问
props
- 变量名和id名没有冲突
在使用 v-for
时,您需要了解并且必须的下一件事正在添加 :key
到充当唯一 ID 并让 Vue
的元素检测到 v-for
中的每个元素都是唯一的.使用:key
时需要注意的一件事是的,你不能使用 :key
在 <template>
上标签。
使用 v-if
添加验证会是个好主意,所以 v-for
仅在数组不为空时执行。
<div id="sheets">
<template v-if="sheets.length">
<Card v-for="(sheet,index) in sheets" :key="index" :info="sheet" />
</template>
</div>
编辑 1: 正如 Michal 在评论部分提到的,使用 index
在调试问题时可能会导致困难。您可以使用 :key="sheet"
或者如果 sheet
是对象,包括一些独特的 id
在其中,然后使用 :key="sheet.id"
并摆脱 index
// use this if sheet is not an object
<div id="sheets">
<template v-if="sheets.length">
<Card v-for="sheet in sheets" :key="sheet" :info="sheet" />
</template>
</div>
或
// use this if sheet is an object having some unique id in it
<div id="sheets">
<template v-if="sheets.length">
<Card v-for="sheet in sheets" :key="sheet.id" :info="sheet" />
</template>
</div>
关于javascript - 无法在 Vue js 的 v-for 循环中动态地将 Prop 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73038032/