报错‘<template v-for>‘ cannot be keyed. Place the key on real elements instead
·
报错’<template v-for>’ cannot be keyed. Place the key on real elements instead
报错的使用场景
在vue3的项目中,不免会遇到v-if和v-for一起使用,但我们知道,这两个是不可以一起使用的,v-for 具有比 v-if 更高的优先级,所以我们需要把v-for写到template中,但是控制台会提示:
'<template v-for>' cannot be keyed. Place the key on real elements instead
解决方法
在 Vue 2中,<template> 标签不能拥有 key,不过,你可以为其每个子节点分别设置 key
<template v-for="i in list">
<div :key="'index-' + i.id"></div>
</template>
在 Vue 3 中,key 则应该被设置在 <template> 标签上
<template v-for="(i, index) in list" :key="index">
<div>...</div>
<span>...</span>
</template>
但是我在使用的时候VScode总是一直报错冒红,但是程序是可以运行的,但总看着不舒服,可以尝试将:key="index"写在我们循环的节点上面,程序也是可以运行的。
<template v-for="i in list">
<div v-if="true" :key="item.id"></div>
<span v-else></span>
</template>
按照官网说的key 则应该被设置在 <template> 标签上的话,可以修改.eslintrc.js的配置,在rules的规则上添加:
'vue/no-v-for-template-key': 'off'
或者将将template标签改为div等其他标签,这样的话会多出一个多余的div标签。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)