v-for中key屬性的作用


key

當 Vue.js 用 v-for 正在更新已渲染過的元素列表時,它默認用“就地復用”策略。如果數據項的順序被改變,Vue 將不會移動 DOM 元素來匹配數據項的順序, 而是簡單復用此處每個元素,並且確保它在特定索引下顯示已被渲染過的每個元素。我們在使用的使用經常會使用index(即數組的下標)來作為key,但其實這是不推薦的一種使用方法。

 

舉個index作為key的例子:

 1 const list = [
 2     {
 3         id: 1,
 4         name: 'test1',
 5     },
 6     {
 7         id: 2,
 8         name: 'test2',
 9     },
10     {
11         id: 3,
12         name: 'test3',
13     },
14 ]
1 <div v-for="(item, index) in list" :key="index" >{{item.name}}</div>

下面我們來看一看用index作為key的缺陷

1.在最后一條數據后再加一條數據

 1 const list = [
 2     {
 3         id: 1,
 4         name: 'test1',
 5     },
 6     {
 7         id: 2,
 8         name: 'test2',
 9     },
10     {
11         id: 3,
12         name: 'test3',
13     },
14     {
15         id: 4,
16         name: '我是在最后添加的一條數據',
17     },
18 ]

運行結果:

之前的數據                         之后的數據

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

2.在中間插入一條數據

 1 const list = [
 2     {
 3         id: 1,
 4         name: 'test1',
 5     },
 6     {
 7         id: 4,
 8         name: '我是插隊的那條數據',
 9     }
10     {
11         id: 2,
12         name: 'test2',
13     },
14     {
15         id: 3,
16         name: 'test3',
17     },
18 ]

運行結果:

之前的數據                         之后的數據

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

通過上面清晰的對比,發現用index作為key的方式除了第一個數據可以復用之前的之外,另外三條數據都需要重新渲染。然而用每條數據的id作為key來標識數據的唯一性這種方式,只有新添加的數據需要渲染,其他的數據復用之前的數據。顯然后一種方式更加的高效。

建議盡可能在使用 v-for 時提供 key,除非遍歷輸出的 DOM 內容非常簡單,或者是刻意依賴默認行為以獲取性能上的提升。

至於其中的原因是因為Virtual DOM 使用Diff算法實現的,詳解請參考官方文檔或參考https://www.jianshu.com/p/342e2d587e69博客

 

 

本文轉載於:

作者:funnycoderstar
鏈接:https://www.jianshu.com/p/342e2d587e69
來源:簡書

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM