Home > Article > Web Front-end > Let’s take a look at the role of the key attribute in v-for!
Related recommendations: "vue.js Tutorial"
In fact, it is not just vue, react will also ask for each item when performing list rendering. Add the key attribute to each component.
To explain the role of key, we have to introduce the Diff algorithm of virtual DOM first.
We know that both vue and react implement a set of virtual DOM, which allows us to re-render the page without directly operating DOM elements and only operating data. The principle hidden behind it is its efficient Diff algorithm.
The Diff algorithm of vue and react's virtual DOM is roughly the same. Its core is based on two simple assumptions:
Two identical components produce similar DOM structures , different components generate different DOM structures.
A group of nodes at the same level, they can be distinguished by a unique id.
Based on the above two assumptions, the complexity of the virtual DOM Diff algorithm is reduced from O(n^3) to O(n).
Here we borrow a picture from React's diff algorithm to briefly explain:
When the data on the page changes, the Diff algorithm will only compare the same level. Node:
If the node types are different, directly kill the previous node, create and insert a new node, and the subsequent child nodes of this node will not be compared.
If the node types are the same, the attributes of the node will be reset to realize the update of the node.
When there are many identical nodes in a certain layer, that is, list nodes, the update process of the Diff algorithm also follows the above principles by default.
For example, in the following situation:
We hope to add an F between B and C. The default execution of the Diff algorithm is as follows:
That means updating C to F, D to C, E to D, and finally inserting E. Isn’t it very inefficient?
So we need to use key to uniquely identify each node. The Diff algorithm can correctly identify this node and find the correct location to insert the new node.
So in a word, the main role of key is to update the virtual DOM efficiently. In addition, when using transition switching of elements with the same tag name in Vue, the key attribute will also be used. The purpose is also to allow Vue to distinguish them.
Otherwise, Vue will only replace its internal attributes and not trigger the transition. Effect.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of Let’s take a look at the role of the key attribute in v-for!. For more information, please follow other related articles on the PHP Chinese website!