报错’<template v-for>’ cannot be keyed. Place the key on real elements instead

报错的使用场景

vue3的项目中,不免会遇到v-ifv-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标签。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐