key
attribute
- NEW:对于
v-if
/v-else
/v-else-if
的各分支项key
将不再是必须的,因为现在 Vue 会自动生成唯一的key
。- BREAKING:如果你手动提供
key
,那么每个分支必须使用唯一的key
。你不能通过故意使用相同的key
来强制重用分支。
- BREAKING:如果你手动提供
- BREAKING:
<template v-for>
的key
应该设置在<template>
标签上 (而不是设置在它的子节点上)。
特殊的 key
attribute 被用于提示 Vue 的虚拟 DOM 算法来保持对节点身份的持续跟踪。这样 Vue 可以知道何时能够重用和修补现有节点,以及何时需要对它们重新排序或重新创建。关于其它更多信息,可以查看以下章节:
这个示例在 Vue 3.x 中仍能正常工作。但是我们不再建议在 v-if
/v-else
/v-else-if
的分支中继续使用 key
attribute,因为没有为条件分支提供 key
时,也会自动生成唯一的 key
。
<!-- Vue 3.x -->
<div v-if="condition">Yes</div>
<div v-else>No</div>
在 Vue 2.x 中 <template>
标签不能拥有 key
。不过你可以为其每个子节点分别设置 key
。
<!-- Vue 2.x -->
<template v-for="item in list">
<span :key="item.id">...</span>
</template>
类似地,当使用 <template v-for>
时存在使用 v-if
的子节点,key
应改为设置在 <template>
标签上。
<template v-for="item in list">
<div v-if="item.isVisible" :key="item.id">...</div>
<span v-else :key="item.id">...</span>
</template>
<!-- Vue 3.x -->
<template v-for="item in list" :key="item.id">
<div v-if="item.isVisible">...</div>