key attribute

    • NEW:对于 v-if/v-else/v-else-if 的各分支项 key 将不再是必须的,因为现在 Vue 会自动生成唯一的 key
      • BREAKING:如果你手动提供 key,那么每个分支必须使用唯一的 key。你不能通过故意使用相同的 key 来强制重用分支。
    • 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

    1. <!-- Vue 3.x -->
    2. <div v-if="condition">Yes</div>
    3. <div v-else>No</div>

    在 Vue 2.x 中 <template> 标签不能拥有 key。不过你可以为其每个子节点分别设置 key

    1. <!-- Vue 2.x -->
    2. <template v-for="item in list">
    3. <span :key="item.id">...</span>
    4. </template>

    类似地,当使用 <template v-for> 时存在使用 v-if 的子节点,key 应改为设置在 <template> 标签上。

    1. <template v-for="item in list">
    2. <div v-if="item.isVisible" :key="item.id">...</div>
    3. <span v-else :key="item.id">...</span>
    4. </template>
    5. <!-- Vue 3.x -->
    6. <template v-for="item in list" :key="item.id">
    7. <div v-if="item.isVisible">...</div>