virtual dom concept

1. Concept:


Virtual DOM is actually using a native JS object to describe a DOM node. In fact, it is just an abstraction of the real DOM. Finally, this tree can be mapped to the real environment through a series of operations.

It is equivalent to making a cache between js and DOM, using patch (diff algorithm) to compare the old and new virtual DOM records to an object and update it on demand, and finally create a real DOM

2. Principle process of virtual dom


Template ==> rendering function ==> virtual DOM tree ==> real DOM

    Vuejs converts the template (template) into a rendering function (render) by compiling, and executing the rendering function can get a virtual node tree

    When operating on the Model, it will trigger the Watcher object in the corresponding Dep. The Watcher object will call the corresponding update to modify the view.

The realization principle of virtual DOM mainly includes the following three parts:

    Simulate the real DOM tree with JavaScript objects and abstract the real DOM;
    diff algorithm—compare the difference between two virtual DOM trees;
    pach algorithm—apply the difference between two virtual DOM objects to the real DOM tree.

Graphic: insert image description here

        Rendering function: The rendering function is used to generate Virtual DOM.
        VNode virtual node: It can represent a real dom node. The VNode can be rendered into a dom node through the createElement method. Simply put, vnode can be understood as a node description object, which describes how to create a real DOM node
        patch (also called patching algorithm): the core part of virtual DOM, which can render vNode into a real DOM, this process It is to compare the differences between the old and new virtual nodes, and then find out the nodes that need to be updated according to the comparison results.

3. Benefits of virtual DOM


    Have the advantage of cross-platform – Since Virtual DOM is based on JavaScript objects and does not depend on the real platform environment, it has cross-platform capabilities, such as browser platforms, Weex, Node, etc.
    The operation of DOM is slow, and the efficiency of js operation is high. We can put the DOM comparison operation in the JS layer to improve efficiency. Use the patching algorithm to calculate the nodes that really need to be updated, minimize DOM operations, and thus significantly improve performance. Virtual DOM is essentially a cache between JS and DOM.
    Improving rendering performance The advantage of Virtual DOM is not a single operation, but a reasonable and efficient update of the view under a large number of frequent data updates. Virtual DOM is designed to
    solve browser performance problems.

Guess you like

Origin blog.csdn.net/m0_52578688/article/details/125284019