SRC \core\vdom\ patch.js-updatechildren () SRC \core\vdom\ patch.js-updatechildren ()
The test code is as follows
<! DOCTYPEhtml>
<html>
<head>
<title>03- The function and principle of key?</title>
</head>
<body>
<div id="demo">
<p v-for="item in items" :key="item">{{item}}</p> </div>
<script src=".. /.. /dist/vue.js"></script>
<script>
// Create an instance
const app = new Vue({
el: '#demo'.data: { items: ['a'.'b'.'c'.'d'.'e'] },
mounted () {
setTimeout(() = > {
this.items.splice(2.0.'f')},2000); }});</script>
</body>
</html>
Copy the code
The above example recreates the following process
Do not use the key
The previous two times of comparing A/B, patchVnode was performed twice, but the update did not occur
Compare C/D/E for the last three times, conduct patchVnode for three times, update for three times, create and insert operation for the last time, and insert E at the end
If you use key(there’s a head and tail fake guess strategy)
Patch was performed for 5 times, but no update occurred. Finally, F was created and inserted before C
// First cycle patch A A B C D E
A B F C D E
// Patch B B C D E
B F C D E
// Patch E C D E
F C D E
// Cycle patch D C D for the 4th time
F C D
// Cycle patch C C for the 5th time
F C
// oldCh is finished, the remaining F in newCh is created and inserted in front of C
Copy the code
The source code is as follows
PatchVnode can be used only if the old and new virtual nodes are the sameIf no key is set, a.key===b.key = true(because both are undefined)
Take a look at the specific code in the source code:
conclusion
-
Key is mainly used to update virtual DOM efficiently. The principle is that vUE can accurately judge whether two nodes are the same or not through key during patch, thus avoiding frequent updates of different elements, making the whole patch process more efficient, reducing DOM operation and improving performance.
-
In addition, not setting a key can cause hidden bugs when the list is updated
-
Vue also uses the key attribute when transitioning between elements with the same label name. The purpose is to allow VUE to distinguish between them. Otherwise, VUE will only replace its internal attributes without triggering transitions.