Why use key for vue list rendering

What is the key?

The special attribute of key is mainly used in Vue's virtual DOM algorithm to identify VNodes when comparing new and old nodes. If you don't use keys, Vue will use an algorithm that minimizes dynamic elements and tries to modify/reuse elements of the same type in place as much as possible. When using the key, it will rearrange the order of the elements based on the change of the key, and will remove the elements whose key does not exist.

Child elements with the same parent element must have a unique key. Duplicate keys will cause rendering errors.

Why use key

First of all, Vue will render elements as efficiently as possible. It usually reuses existing elements instead of rendering from scratch.
Vue provides a way to express "These two elements are completely independent. Don't reuse them." Just add A key attribute with a unique value is enough

For v-for, the "in-place update" strategy used by default (that is, no key is used), that is, if the order of data items is changed, Vue will not move DOM elements to match the order of data items, but in-place Update each element. This default mode is efficient. So why use Key? This is to give Vue a hint so that he can track the identity of each node, thereby reusing and reordering existing elements.

The role of the key is to force the component to be updated when the data changes, avoiding the side effects of "in-place reuse"

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/113791450