The reason for using key in v-for

The reason for using key in v-for is:

The key can only be a string or a number.
The key must be the only
key: Function: Improve rearrangement efficiency and in-place multiplexing

  • The key can identify the uniqueness of each element in the list, which is convenient for Vue to efficiently update the virtual DOM.
  • The key is mainly used in the dom diff algorithm. The diff algorithm is a peer comparison, comparing the key and the tag name on the current tag. If they are the same, only the element will be moved, and will not be recreated or deleted.
  • If there is no key, Vue will use the "in-place multiplexing" strategy. If the order of the data items changes, Vue will not move the DOM elements to match the changes of the data items, but simply reuse each element in the original position.
  • Try not to use the index value index as the key, because the index will change with the addition and deletion of data, causing the key to become invalid1. It is better to use unique identification in the data, such as id, etc.

Here is an example of using key in v-for:

<ul>
  <li v-for="item in items" :key="item.id">
    {
   
   { item.name }}
  </li>
</ul>

Here, we used item.id as key because it is unique. In this way, when the items array changes, Vue can correctly update and move the corresponding elements according to the key, instead of re-rendering the entire list.

Guess you like

Origin blog.csdn.net/m0_53579196/article/details/130533408