We know that Vue uses a virtual DOM to update nodes, which saves browser overhead. How does Vue internally update the DOM by comparing old and new nodes using diff algorithms? This article will analyze the internal DIFF algorithm mechanism of Vue from the source point of view. First, we enter the diff algorithm which is the definition of the core function patch. In core/vdom/patch.js,
There is a sameVnode method to determine whether the old and new nodes are the same. If so, enter the patchVnode method in the red box, which is the core of diff algorithm.
If the new node is not a plain text node, the updateChildren method is required if the child nodes of both the old and new nodes exist. Otherwise, if the new child node exists, add the new child node to the virtual DOM tree; if the old child node exists, remove the old child node from the DOM tree. If the old child node is text, empty it.
Let’s look at the updateChildren method, which is used to compare two sets of child nodes
This method first sets the first and last four cursors and their corresponding nodes, and then defines the variables needed for subsequent lookups. Then enter the cycle. If the new start node is the same as the old start node, execute the patchVnode method and move the cursor backwards. If the two groups of end nodes are the same, run patchVnode to move the cursor forward. If the old start node is the same as the new end node, insert the new node before the old node. If the old end point is the same as the new start node, insert the new node after the old node. If the two groups and the first and last nodes of the nodes are not the same, the new start node will be found in the old node group. If it cannot be found, a new node will be inserted into the virtual DOM tree. If it is found, the node will be updated.
This is the principle of the virtual DOM tree diff algorithm in Vue.