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.

1

2

3

<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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

<!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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
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.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles