The introduction

Today we learned about the relationship between key and diff algorithms in V-for and how Vue effectively renders DOM.

V – for the key

The official explanation

  • The key attribute is mainly used in the virtual DOM algorithm of Vue to identify VNodes when comparing old and new nodes
  • If keys are not used, Vue uses an algorithm that minimizes dynamic elements and tries to modify/reuse the same type of elements in place whenever possible
  • With a key, it rearranges elements based on the change in the key, and removes/destroys elements where the key does not exist.
  • It’s hard to understand !!!! Go straight to case

case

  • Insert f into [a,b,c,d]
    • The array has changed. Re-loop the V-for
    • A stays the same, B stays the same, C becomes F, D becomes C, and then I add d
    • A, B, C,d, I’m going to add an F
  • Obviously, the third method is the most efficient
  • Vue actually calls two different methods with and without a key
    • If there is a key, use the patchKeyedChildren method
    • No key, so long patchUnkeyedChildren method

On the source code

Vue source code for key judgment

Operation without key (source code)

  • Operations without keys are divided into three steps
    1. First get the length of the old and new nodes and remove the minimum length
    2. Traverse nodes with small length, patch old and new nodes in turn (easy to understand is to compare node types and content)
    3. Judge the length of the old node and the new one. If the old one is short, add a new node; otherwise, delete the node
Have key to perform operations (source code)

  • It is divided into 5 steps
    1. The loop is iterated and compared from the beginning. If the key is inconsistent, break the loop

2. Perform traversal and comparison from the end3. If a new node still exists after the traversal of the old node is complete, add a node4. If the new node is traversed but the old node still exists, remove the old node5. In the most characteristic case, there are many unknown or out-of-order nodes in the middleIn this case, vUE’s approach is to reuse the repeated nodes as much as possible, remove the old nodes that do not appear in the new node, and add the nodes that appear in the new node but do not appear in the old node

Note: the key value in v-for is used as a key value.