In fact, it's not just that the vue,react is also required to add the key to each component when performing a list rendering.
To explain the role of key, we have to first introduce the Virtual Dom diff algorithm.
We know that Vue and react both implement a set of virtual DOM, so that we can render the page without manipulating the DOM elements and simply manipulating the data. And the principle behind it is its efficient diff algorithm.
The diff algorithm for the virtual Dom of Vue and react is roughly the same, and its core is based on two simple assumptions:
1, two identical components produce a similar DOM structure, and different components produce different DOM structures.
2, a group of nodes at the same level, they can be distinguished by a unique ID.
Based on the above two-point hypothesis, the complexity of the virtual Dom's diff algorithm is reduced from O (n^3) to O (n).
Here we borrow a picture from react's diff algorithm to illustrate briefly:
When the page's data changes, the diff algorithm only compares nodes at the same level:
If the node type is different, kill the previous node directly, create and insert a new node, and no longer compare the node's child nodes.
If the node type is the same, the node's properties are reset to update the node.
When a layer has many identical nodes, that is, the list node, the update process of the diff algorithm is followed by default.
For example, the following is the case:
We want to be able to add a f,diff algorithm between B and C. This is done by default:
That is, the C update to f,d update to c,e update to D, and finally insert E, is not very efficient?
So we need to use key to make a unique identifier for each node, and the diff algorithm will identify the node correctly and find the correct location to insert the new node.
So in a word,Key's role is mainly to update the virtual DOM efficiently. In addition, the key property is used in Vue for transitions that use the same tag name elements, and the purpose is to let Vue differentiate them, otherwise the Vue will only replace its internal properties without triggering the transition effect.
Diagram of v-for in Vue: function of key, virtual Dom diff algorithm