The usage of v-for in vue and its key

Foreword:

        When using v-for in vue, we generally need to add a key to indicate its uniqueness, so why do we need to add this key, let’s talk about it here

Usage of v-for:


<ul>
    <li v-for='(item,index) in arr' :key='"demo"+index'>{
   
   {item}}<li>
</ul>

data里面定义:
arr:[]

可以简单的这样理解:加了key(一定要具有唯一性) id的checkbox跟内容进行了一个关联。是我们想达到的效果

I have checked the relevant documents, and the legend is very clear.

The Diff algorithm of the virtual DOM of vue and react is roughly the same. Its core is based on two simple assumptions.
First , let's talk about the processing method of the diff algorithm. Compare the nodes of the same layer of the dom tree before and after the operation. Picture:

 

before.png

When there are many identical nodes in a layer, that is, list nodes, the update process of the Diff algorithm also follows the above principles by default.
For example, this situation:

 

3297464-ee627869a6714336.jpg

 

We hope we can add an F between B and C. The Diff algorithm is executed by default like this:

 

3297464-d912523aac5fd108.jpg


That is, update C to F, D to C, E to D, and finally insert E. Is it very inefficient?

So we need to use the key to make a unique identification for each node, the Diff algorithm can correctly identify this node, find the correct location area to insert a new node.

 

3297464-650689b4bd4b9eb6.jpg

 

The list loop in vue needs to add: key="unique identifier" The unique identifier can be the id index in the item, etc., because the vue component is highly reused and the key can identify the uniqueness of the component. In order to better distinguish each component, the key function is mainly In order to efficiently update the virtual DOM

Reference address: https://www.jianshu.com/p/4bd5e745ce95

Guess you like

Origin blog.csdn.net/weixin_44727080/article/details/113178882