This is the 9th day of my participation in Gwen Challenge

preface

Styles written in template in Vue are converted to the virtual DOM during compilation and then to the real DOM during compilation. Is virtual DOM tree structure, and now there is such a scenario, we created a virtual DOM and then change the virtual DOM node information, generates new trees and old trees at this time, will the two tree in the vue diff algorithm, and found out where to change, to replace locally, that will make the page rendering consume less.

Find out where the old and new trees are changed and where they are different. There are four conditions corresponding to the comparison between the old and new trees:

  • If there is no new tree node, the node has been deleted from the old tree.

  • If both the old tree node and the new tree node are strings, but the old and new nodes are not equal, the text is different and the text has been modified.

  • If the new tree and the old tree have the same element type such as ‘div’ == ‘div’, compare their attributes to see if they are consistent. If they are inconsistent, the attributes have been modified.

  • If the element types of the old and new trees do not match, an element substitution has taken place.

In contrast where not at the same time, there is a need to pay attention to the point, because is virtual DOM tree structure, so we use recursive traversal tree, we pass in a subscript recursively, used to record the recursion at that time that the new and old tree is different, the whole DOM tree through, we can get an object, it records the different point, new and old tree And it changed the time it recursed. Such as:

Above: recursion first found the change of the subscript for blue frame 0, 3, 4 minor changes were found in the old and new tree, in order to use object + subscript records changed in the new and old trees, in the form of this kind of treatment when we convert real DOM, can according to the object node of local update change.

Now that we have identified the different locations in the old and new trees in the previous steps, we are ready to update them.

conclusion

The idea of locally updating real DOM nodes is as follows: the recursion subscript of the old recursive tree is increased by one each time, and the variable information set object in the figure above is extracted with this subscript. If the object node extracted with the subscript is not empty, it means that the information of the current node is changed.