Home Web Front-end JS Tutorial What is vue virtual DOM? Usage of vue's virtual DOM

What is vue virtual DOM? Usage of vue's virtual DOM

Aug 09, 2018 am 11:00 AM

Vue’s virtual DOM uses js to simulate the DOM structure. The content of this article is to introduce to friends what vue virtual DOM is? As well as the usage of vue's virtual DOM, let's take a look at the specific content in the article.

1. Why virtual DOM is needed

We wrote a simple Vue-like framework from scratch, in which template parsing and rendering are completed through the Compile function. , document fragmentation is used instead of directly operating the DOM elements in the page. After the data is changed, the real DOM is inserted into the page through the appendChild function.

Although document fragments are used, the real DOM is still operated.

We know that operating DOM is expensive, so vue2.0 uses virtual DOM to replace the operation of real DOM, and finally uses some mechanism to complete the update of real DOM and render the view.

The so-called virtual DOM actually uses JS to simulate the DOM structure, and puts the DOM change operations on the JS layer to minimize the operations on the DOM (I personally think it is mainly because Operating JS is countless times faster than operating DOM, and JS is highly efficient). Then compare the changes in the virtual DOM twice before and after, and only the changed parts will be re-rendered, while the unchanged parts will not be re-rendered.

For example, we have the following DOM structure.

<ul id="list">
      <li class="item1">Item 1</li>
      <li class="item2">Item 2</li></ul>
Copy after login

We can completely use JS objects to simulate the above DOM structure. After simulation, it will become the following structure.

var vdom = {
    tag: &#39;ul&#39;,
    attr: {
        id: &#39;list&#39;,
    },
    children: [
        {
            tag: &#39;li&#39;,
            attrs: {
                className: &#39;item&#39;,
                children: [&#39;Item 1&#39;]
            },
        },
        {
            tag: &#39;li&#39;,
            attrs: {
                className: &#39;item&#39;,
                children: [&#39;Item 2&#39;]
            }
        }
    ]

}
Copy after login

It must be noted that the DOM structure simulated by JS does not simulate the properties and methods on all DOM nodes (because the properties of the DOM node itself are very (this is also a point where DOM operations consume performance), but only simulates a part of the properties and methods related to data operations.

2. Usage of vue virtual DOM

Vue introduced vdom in version 2.0. Its vdom is based on modifications made by the snabbdom library. snabbdom is an open source vdom library.

The main function of snabbdom is to convert the incoming JS simulated DOM structure into a virtual DOM node.

First convert the JS simulated DOM structure into a virtual DOM through the h function, and then convert the virtual DOM into a real DOM through the patch function and render it into the page.

In order to ensure the minimum rendering of the page, snabbdom introduces the Diff algorithm, which uses the Diff algorithm to find out the difference between the two virtual DOMs before and after, and only updates the changed DOM nodes without re-rendering them as changed ones. DOM node.

Here I am not going to analyze the source code of snabbdom to explain how snabbdom does this (mainly because it is not at that level at this stage, haha. Moreover, many students have already done similar analysis , relevant links are attached at the end of the article).

I will look at how the virtual DOM in Vue completes view rendering from the perspective of using snabbdom.

Let’s first take a look at the functions of the two core APIs in snabbdom.

  • h() function: Convert the incoming JS simulated DOM structure template into vnode. (vnode is a pure JS object)

  • patch() function: Render virtual DOM nodes into the page.

We provide an example to see the actual function of snabbdom.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title></head><body>
    <p id="container"></p>
    <button id="btn-change">change</button>
    <!-- 引入snabbdom库,先不必纠结为什么这样引入,以及每个文件的作用。本篇文章只是介绍一下虚拟DOM的工作方式,并不涉及原理解析
    主要是因为博主目前功力尚浅,有兴趣的小伙伴可以另行研究 -->
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-class.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-props.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-style.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-eventlisteners.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.1/h.js"></script>
    <script>
        //定义patch函数
        var patch = snabbdom.init([
            snabbdom_class,
            snabbdom_props,
            snabbdom_style,
            snabbdom_eventlisteners
        ])        //定义h函数
        var h = snabbdom.h;        //生成一个vnode
        var vnode = h(&#39;ul#list&#39;,{},[
            h(&#39;li.item&#39;,{},[&#39;Item 1&#39;]),
            h(&#39;li.item&#39;,{},[&#39;Item 2&#39;]),
        ])
     //console.log(vnode);
        //获取container
        var container = document.getElementById(&#39;container&#39;);
        patch(container,vnode);//初次渲染

        var btn = document.getElementById(&#39;btn-change&#39;);
        btn.onclick = function() {            
        var newVnode = h(&#39;ul#list&#39;,{},[
                h(&#39;li.item&#39;,{},[&#39;Item 1&#39;]),
                h(&#39;li.item&#39;,{},[&#39;Item B&#39;]),
                h(&#39;li.item&#39;,{},[&#39;Item 3&#39;]),
            ])
            patch(vnode,newVnode);//再次渲染       
            vnode = newVnode;//将修改后的newVnode赋值给vnode              
            }    
            </script>
            </body>
            </html>
Copy after login

Idea analysis:

  • We first create a virtual DOM node through the h function , render the virtual DOM to the page through the patch function.

  • When the btn button is clicked, the data of the ul#list list is updated, the value of the second li element is changed and a new li element is added, and the value of the first li element is changed. No change. We again render the updated data to the page through the patch function. You can see that only the second and third li are updated, and the first li is not re-rendered because it has not changed.

The core of template parsing and rendering in vue is: first parse the template through functions similar to snabbdom's h() and patch() into vnode. If it is the first rendering, the vnode is rendered to the page through patch(container,vnode). If it is the second rendering, through patch(vnode,newVnode), first compare the difference between the original vnode and newVnode through the Diff algorithm to Re-render the page with minimal effort.

Recommended related articles:

The object of diff is the virtual dom

The above is the detailed content of What is vue virtual DOM? Usage of vue's virtual DOM. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles