Is vuejs a virtual DOM?

青灯夜游
Release: 2023-01-07 11:47:22
Original
3044 people have browsed it

vuejs is a virtual DOM; Vue.js2.0 introduced the Virtual DOM (virtual DOM) mechanism, which increased the initial rendering speed by 2-4 times and greatly reduced memory consumption. The advantages of virtual DOM: it can cross platforms, improve efficiency, improve rendering performance, etc.

Is vuejs a virtual DOM?

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

Vue.js 2.0 introduces Virtual DOM, which is 2-4 times faster than the initial rendering speed of Vue.js 1.0 and greatly reduces memory consumption. So, what is Virtual DOM? Why do you need Virtual DOM? How does it improve page rendering efficiency? This is the question this article will explore.

The process of converting a template into a view

Before formally introducing Virtual Dom, we need to first understand the entire process of converting a template into a view (as shown below):

  • Vue.js converts the template into a rendering function (render) through compilation. By executing the rendering function, a virtual node tree can be obtained.
  • When operating the Model, it will Trigger the Watcher object in the corresponding Dep. The Watcher object will call the corresponding update method to modify the view. This process mainly involves comparing the differences between the old and new virtual nodes, and then performing DOM operations based on the comparison results to update the view.

To put it simply, in the underlying implementation of Vue, Vue compiles the template into a virtual DOM rendering function. Combined with Vue's own response system, when the state changes, Vue can intelligently calculate the minimum cost of re-rendering the component and apply it to the DOM operation.

Let’s first explain the concepts in the above picture:

  • Rendering function: The rendering function is Used to generate Virtual DOM. Vue recommends using templates to build our application interface. In the underlying implementation, Vue will compile the template into a rendering function. Of course, we can also write the rendering function directly without writing a template to obtain better control.

  • VNode virtual node: It can represent a real dom node. VNode can be rendered into a dom node through the createElement method. Simply put, vnode can be understood asnode description object, which describes how to create a real DOM node.

  • patch (also called patching algorithm): The core part of virtual DOM, it can render vnode into real DOM. This process is to compare the old and new virtual nodes. What are the differences between them, and then find out the nodes that need to be updated based on the comparison results and update them. We can see this from the meaning of the word. Patch itself means patch or repair. Its actual function is to modify the existing DOM to update the view. Vue's Virtual DOM Patching algorithm is based on the implementation ofSnabbdom, and many adjustments and improvements have been made on these foundations.

What is Virtual DOM?

Virtual DOM is actually a tree based on JavaScript objects (VNode nodes). Object attributes are used to describe nodes. In fact, it is just a layer of abstraction of the real DOM. Finally, this tree can be mapped to the real environment through a series of operations.

To put it simply, Virtual DOM can be understood as a simple JS object, and it contains at least three attributes: tag name (tag), attributes (attrs) and child element objects (children). Different frameworks have slightly different naming of these three properties.

For virtual DOM, let’s look at a simple example, as shown in the figure below, which explains in detail the process oftemplate → rendering function → virtual DOM tree → real DOM

What is the role of Virtual DOM?

The ultimate goal of virtual DOM is to render virtual nodes to the view. But if you directly use virtual nodes to overwrite old nodes, there will be many unnecessary DOM operations. For example, there are many li tags under a ul tag, and only one li has changed. In this case, if a new ul is used to replace the old ul, these unnecessary DOM operations will cause a waste of performance.

In order to avoid unnecessary DOM operations, during the process of mapping virtual nodes to views, the virtual DOM compares the virtual nodes with the old virtual nodes (oldVnode) used in the last rendering of the view to find out what is really needed. Updated nodes are used to perform DOM operations, thereby avoiding operations on other DOMs that do not need to be modified.

In fact, virtual DOM mainly does two things in Vue.js:

  • Provide virtual node vnode corresponding to the real DOM node
  • Convert the virtual node vnode Compare with the old virtual node oldVnode, and then update the view

Why is Virtual DOM needed?

  • Has cross-platform advantages

Since Virtual DOM is based on JavaScript objects and does not rely on the real platform environment, it has cross-platform advantages. Capabilities, such as browser platform, Weex, Node, etc.

  • Operation DOM is slow, but js runs efficiently. We can put the DOM comparison operation on the JS layer to improve efficiency.

Because the execution speed of DOM operations is far slower than that of Javascript, therefore, a large number of DOM operations are moved to Javascript, and the patching algorithm is used to calculate the nodes that really need to be updated, maximizing the Reduce DOM operations, thereby significantly improving performance.

Virtual DOM essentially creates a cache between JS and DOM. It can be compared to the CPU and the hard disk. Since the hard disk is so slow, we will add a cache between them; since the DOM is so slow, we will add a cache between their JS and DOM. The CPU (JS) only operates the memory (Virtual DOM), and finally writes the changes to the hard disk (DOM)

  • Improve rendering performance

The advantages of Virtual DOM are not It lies in a single operation, but in the context of large and frequent data updates, the view can be updated reasonably and efficiently.

In order to achieve efficient DOM operations, an efficient virtual DOM diff algorithm is necessary.We use the core of patch----diff algorithm to find out the nodes that need to be updated in the DOM this time and update them, and not update the others. For example, if you modify a model 100 times and increase it from 1 to 100, then with the cache of Virtual DOM, only the last modification will be patched to the view. What is the implementation process of the diff algorithm?

diff algorithm

Vue’s diff algorithm is modified based on snabbdom.Only between vnodes of the same level Do diff, recursively perform diff of vnodes at the same level, and finally update the entire DOM tree. Because cross-level operations are very few and can be ignored, the time complexity changes from O(n3) to O(n).

The diff algorithm includes several steps:

  • Use JavaScript object structure to represent the structure of the DOM tree; then use this tree to build a real DOM tree and insert it into the document
  • When the state changes, reconstruct a new object tree. Then compare the new tree with the old tree, record the differences between the two trees
  • Apply the recorded differences to the real DOM tree constructed, and the view will be updated

Implementation process of diff algorithm

diff algorithm itself is very complex and difficult to implement. This article simplifies the complexity and briefly introduces the following two core function implementation processes:

  • patch(container,vnode): During the initial rendering, the VDOM is rendered into a real DOM and then inserted into the container.
  • patch(vnode,newVnode): When rendering again, compare the new vnode with the old vnode, and then apply the difference to the real DOM tree built.

1. patch(container,vnode)

Through this function, VNode can be rendered into a real DOM. Through the following simulation code, we can understand the general Process:

function createElement(vnode) { var tag = vnode.tag var attrs = vnode.attrs || {} var children = vnode.children || [] if (!tag) { return null } // 创建真实的 DOM 元素 var elem = document.createElement(tag) // 属性 var attrName for (attrName in attrs) { if (attrs.hasOwnProperty(attrName)) { // 给 elem 添加属性 elem.setAttribute(attrName, attrs[attrName]) } } // 子元素 children.forEach(function (childVnode) { // 给 elem 添加子元素,如果还有子节点,则递归的生成子节点。 elem.appendChild(createElement(childVnode)) // 递归 }) // 返回真实的 DOM 元素 return elem }
Copy after login

2. patch(vnode,newVnode)

Here we only consider how vnode compares with newVnode:

function updateChildren(vnode, newVnode) { var children = vnode.children || [] var newChildren = newVnode.children || [] // 遍历现有的children children.forEach(function (childVnode, index) { var newChildVnode = newChildren[index] // 两者tag一样 if (childVnode.tag === newChildVnode.tag) { // 深层次对比,递归 updateChildren(childVnode, newChildVnode) } else { // 两者tag不一样 replaceNode(childVnode, newChildVnode) } } )}
Copy after login

Related recommendations :《vue.js tutorial

The above is the detailed content of Is vuejs a virtual DOM?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!