index为什么不能作为v-for的key?
一、为什么要使用key?
key 的作用主要是为了高效地更新虚拟DOM。
例如,在B和C之间插入F:
Diff 算法默认执行的过程:
这种做法C更新成F,D更新成C,E更新成D,最后再插入E,这样效率不高,且性能不够好。
但如果使用了key给每个节点做一个唯一标识,Diff算法就能正确地识别这个节点,找到正确的位置插入新的节点。
二、index为什么不能作为v-for的key?
以下面代码为例,删除 'one':
<template>
<div v-for="(item, index) in list" :key="index" >{{item.num}}</div>
</template>
const list = [
{
id: 0,
num: "zero"
},
{
id: 1,
num: "one"
},
{
id: 2,
num: "two"
},
{
id:3,
num:"three"
}
];
删除前:
key | id | index | num |
---|---|---|---|
0 | 0 | 0 | zero |
1 | 1 | 1 | one |
2 | 2 | 2 | two |
3 | 3 | 3 | three |
删除后:
key | id | index | num |
---|---|---|---|
0 | 0 | 0 | zero |
1 | 2 | 1 | two |
2 | 3 | 2 | three |
此时,除zero外,two和three因为被发现与相应key的绑定关系有变化,所以被重新渲染,容易影响性能。