Summary of Vue front-end interview questions (32) Detailed explanation of the role of Vue Key

The role of key value

Key value: used to manage reusable elements. Because Vue will render elements as efficiently as possible, and usually reuse existing elements instead of rendering from scratch

In fact, not only vue, react also requires the key attribute to be added to each component when performing list rendering.
To explain the role of the key, I have to first introduce the Diff algorithm of the virtual DOM. Both vue and react implement a set of virtual DOM, so that we can re-render the page without directly manipulating DOM elements, only manipulating data. And the principle behind it is its efficient Diff algorithm.
When the page data changes, the Diff algorithm will only compare the same level of data.

Nodes: If the node types are different, directly kill the previous node, then create and insert a new node, without comparing the subsequent child nodes of this node.
If the node type is the same, the attributes of the node will be reset to realize the node update abcde example. At
this time, we need to use the key to make a unique identification for each node, and the Diff algorithm can correctly identify this node and find Insert the new node in the correct position area

In short, the key role is mainly to update the virtual DOM efficiently

Guess you like

Origin blog.csdn.net/Rick_and_mode/article/details/108654809