当前位置:网站首页>Explain the role of key attribute in V-for
Explain the role of key attribute in V-for
2022-06-13 04:43:00 【Dax1_】
Take a chestnut
Not set up key
<div id="app">
<div>
<input type="text" v-model="name">
<button @click="add"> add to </button>
</div>
<ul>
<li v-for="(item, i) in list">
<input type="checkbox"> {
{
item.name}}
</li>
</ul>
<script>
// establish Vue example , obtain ViewModel
var vm = new Vue({
el: '#app',
data: {
name: '',
newId: 3,
list: [
{
id: 1, name: ' Liz ' },
{
id: 2, name: ' Lv buwei ' },
{
id: 3, name: ' Ying Zheng ' }
]
},
methods: {
add() {
// Notice that this is unshift
this.list.unshift({
id: ++this.newId, name: this.name })
this.name = ''
}
}
});
</script>
</div>
When LV Buwei is selected , After adding Nannan, it is really Lisi , It's not what we want , What we want is to add Nannan , One of them is LV Buwei


Set up key
<div id="app">
<div>
<input type="text" v-model="name">
<button @click="add"> add to </button>
</div>
<ul>
<li v-for="(item, i) in list" :key="item.id">
<input type="checkbox"> {
{
item.name}}
</li>
</ul>
<script>
// establish Vue example , obtain ViewModel
var vm = new Vue({
el: '#app',
data: {
name: '',
newId: 3,
list: [
{
id: 1, name: ' Liz ' },
{
id: 2, name: ' Lv buwei ' },
{
id: 3, name: ' Ying Zheng ' }
]
},
methods: {
add() {
// Notice that this is unshift
this.list.unshift({
id: ++this.newId, name: this.name })
this.name = ''
}
}
});
</script>
</div>
Similarly, Lu won the election , After adding Nan Nan, Lu Buwei is still selected .


It's easy to understand : added key( Must be unique ) id Of checkbox With the content . Is what we want to achieve
Why key
- vue In the list loop, you need to add
:key=' Unique identification ', The unique identifier should be id, The aim is to efficiently update the virtual DOM - key It is mainly used for dom diff Algorithm ,diff Algorithm is peer comparison , Compare... On the current tag key And his current tag name , If key Only move when it is the same as the tag name , Elements will not be recreated or deleted
- No, key It is used by default Local reuse Strategy . If the order of the data is changed ,vue Not mobile DOM Element to match changes in data items , Instead, simply reuse each element in its original location , When comparing, it is found that the labels are the same and the values are different , Will reuse the previous location , Put the new value directly in this position , And so on , If there is one more, the last one will be deleted .
- Try not to use index values index do key value , Be sure to use a uniquely identified value , Such as id etc. . Because if you use an array index index by key, When a new element is inserted into the specified position in the array , Because it will be updated again index Indexes , Corresponding to the following virtual DOM Of key All values have been updated , Unnecessary updates will still be made at this time , It's like not adding key equally , therefore index Although it can solve key The problem of no conflict , But it can't solve the problem of reuse . If it's static data , Use index numbers index do key Value is no problem .
Why? key Do not use index
Keep raising a chestnut
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>
The code above uses index As key
Add a piece of data at the end of the list
const list = [
{
id: 1,
name: 'test1',
},
{
id: 2,
name: 'test2',
},
{
id: 3,
name: 'test3',
},
{
id: 4,
name: ' I added a piece of data at the end ',
},
]
At this time, the first three pieces of data are directly reused , Newly render the last piece of data , Use at this time index As key, No problem
Insert a piece of data in the middle
const list = [
{
id: 1,
name: 'test1',
},
{
id: 4,
name: ' I'm the data that jumped the queue ',
}
{
id: 2,
name: 'test2',
},
{
id: 3,
name: 'test3',
},
]
The render data is updated , adopt index Defined key To compare the data before and after , Find out
Previous data Later data
key: 0 index: 0 name: test1 key: 0 index: 0 name: test1
key: 1 index: 1 name: test2 key: 1 index: 1 name: I'm the data that jumped the queue
key: 2 index: 2 name: test3 key: 2 index: 2 name: test2
key: 3 index: 3 name: test3
Through the clear contrast above , It is found that except that the first data can be reused , The other three pieces of data need to be re rendered ;
The best way is to use the unchanged item in the array as key value , Corresponding to project , That is, each data has a unique id, To identify the uniqueness of this data ; Use id As key value , Let's compare and insert a piece of data into the middle , How to render at this time
Previous data Later data
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: I'm the data that jumped the queue
key: 3 id: 3 index: 2 name: test3 key: 2 id: 2 index: 2 name: test2
key: 3 id: 3 index: 3 name: test3
Now the comparison shows that only one piece of data has changed , Namely id by 4 The data of , So just render this piece of data , Others are just before reuse ;
diff Algorithm diagram
diff Processing method of algorithm , Before and after the operation dom Compare the nodes in the same layer of the tree , Contrast layer by layer

In the following usage scenarios :
We hope it can be in B and C Add one between F,Diff This is how the algorithm works by default :

Namely the C Update to F,D Update to C,E Update to D, Finally, insert E, Isn't it very inefficient ?
So we need to use key To give each node a unique identifier ,Diff The algorithm can identify this node correctly , Find the right location and insert a new node .

So in a word ,key The main purpose is to update the virtual environment efficiently DOM. in addition vue When using the transition switch of the same tag name element , It will also use key attribute , Its purpose is to make vue You can tell them apart , otherwise vue It only replaces its internal properties without triggering the transition effect .
summary
- Simply put , No, key when , The state is bound to the location by default , Yes key when , Status basis key The attribute value of is bound to the array element of the response .
- key It's to update the virtual environment more efficiently DOM
- It is recommended to use the fields in the array ( Guarantee uniqueness ) As key Unique identification of , It is not recommended to use index
Reference documents
边栏推荐
- Promise processing JS multithreads get the same processing result after all the results are obtained
- Tita: Xinrui group uses one-to-one talk to promote the success of performance change
- Createanonymousthreadx passes parameters to anonymous threads
- Colab使用教程(超级详细版)及Colab Pro/Pro+评测
- Crawler scrapy framework learning 2
- Vercel uses HTTP caching
- [JS solution] leedcode 200 Number of islands
- Tita:新锐集团采用一对一面谈推动绩效变革成功
- php开发16退出模块
- 用navicat将mysql数据转化为postgresql
猜你喜欢

Uni app Ali font icon does not display

约瑟夫问题

Express scaffold creation

自动评教脚本使用的配置

Record a troubleshooting process - video call cannot be picked up

Cesium:CesiumLab制作影像切片与切片加载

Analysis of the implementation principle of an open source markdown to rich text editor

Redis

2022 ICML | Pocket2Mol: Efficient Molecular Sampling Based on 3D Protein Pockets

【JS解决】leedcode 117. 填充每个节点的下一个右侧节点指针 II
随机推荐
Serial communication learning
Ultra quicksort reverse sequence pair
Win8.1和Win10各自的优势
Day 007: go language string
D 小红的构造题
【JS解决】leedcode 117. 填充每个节点的下一个右侧节点指针 II
Latex operation
Analysis on the usage, response and global delivery of provide/inject
PowerDesigner easy to use
Test question bank and online simulation test for special operation certificate of construction scaffolder (special type of construction work) in 2022
2022氯化工艺操作证考试题库及模拟考试
[JS solution] leedcode 117 Populate the next right node pointer II for each node
Go scheduled task cron package usage
力扣刷题338.比特位计数
【Try to Hack】upload-labs通关(暂时写到12关)
Returns the width and height of an element
Sword finger offer 56 - I. number of occurrences in the array
Time format method on the official demo of uniapp
Third party comment plugin
Get verification code