首次發表在我的博客html
使用v-for
更新已渲染的元素列表時,默認用就地複用
策略;列表數據修改的時候,他會根據key值去判斷某個值是否修改,若是修改,則從新渲染這一項,不然複用以前的元素; 咱們在使用的使用常常會使用index
(即數組的下標)來做爲key
,但其實這是不推薦的一種使用方法;vue
舉個🌰react
const list = [ { id: 1, name: 'test1', }, { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, ] 複製代碼
<div v-for="(item, index) in list" :key="index" >{{item.name}}</div>
複製代碼
上面這種是咱們作項目中經常使用到的一種場景,由於不加key,vue如今直接報錯,因此我使用index做爲key;下面列舉兩種常見的數據更新狀況git
const list = [ { id: 1, name: 'test1', }, { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, { id: 4, name: '我是在最後添加的一條數據', }, ] 複製代碼
此時前三條數據直接複用以前的,新渲染最後一條數據,此時用index
做爲key
,沒有任何問題;github
const list = [ { id: 1, name: 'test1', }, { id: 4, name: '我是插隊的那條數據', } { id: 2, name: 'test2', }, { id: 3, name: 'test3', }, ] 複製代碼
此時更新渲染數據,經過index
定義的key
去進行先後數據的對比,發現算法
以前的數據 以後的數據 key: 0 index: 0 name: test1 key: 0 index: 0 name: test1 key: 1 index: 1 name: test2 key: 1 index: 1 name: 我是插隊的那條數據 key: 2 index: 2 name: test3 key: 2 index: 2 name: test2 key: 3 index: 3 name: test3 複製代碼
經過上面清晰的對比,發現除了第一個數據能夠複用以前的以外,另外三條數據都須要從新渲染;數組
是否是很驚奇,我明明只是插入了一條數據,怎麼三條數據都要從新渲染?而我想要的只是新增的那一條數據新渲染出來就好了markdown
最好的辦法是使用數組中不會變化的那一項做爲key
值,對應到項目中,即每條數據都有一個惟一的id
,來標識這條數據的惟一性;使用id
做爲key
值,咱們再來對比一下向中間插入一條數據,此時會怎麼去渲染ide
以前的數據 以後的數據 key: 1 id: 1 index: 0 name: test1 key: 1 id: 1 index: 0 name: test1 key: 2 id: 2 index: 1 name: test2 key: 4 id: 4 index: 1 name: 我是插隊的那條數據 key: 3 id: 3 index: 2 name: test3 key: 2 id: 2 index: 2 name: test2 key: 3 id: 3 index: 3 name: test3 複製代碼
如今對比發現只有一條數據變化了,就是id
爲4的那條數據,所以只要新渲染這一條數據就能夠了,其餘都是就複用以前的;oop
同理在react中使用map渲染列表時,也是必須加key,且推薦作法也是使用id
,也是這個緣由;
其實,真正的緣由並非vue和react怎麼怎麼,而是由於Virtual DOM 使用Diff算法實現的緣由,
下面大體從虛擬DOM的Diff算法實現的角度去解釋一下
vue和react的虛擬DOM的Diff算法大體相同,其核心是基於兩個簡單的假設:
引用React’s diff algorithm中的例子:
因此咱們須要使用key來給每一個節點作一個惟一標識,Diff算法就能夠正確的識別此節點,找到正確的位置區插入新的節點。
因此一句話,key的做用主要是爲了高效的更新虛擬DOM。另外vue中在使用相同標籤名元素的過渡切換時,也會使用到key屬性,其目的也是爲了讓vue能夠區分它們,不然vue只會替換其內部屬性而不會觸發過渡效果。