Vue.js DOM tree (original) (raw)

Last Updated : 04 Aug, 2022

Vue.js is a javascript framework that is used in building static as well as dynamic webpages and User Interfaces. It offers many lucrative features for developers to use. For example, virtual DOM, component architecture, directives, templates, event binding, and many more.

Document Object Model (DOM) is a tree-like representation of a webpage that treats every node as a javascript object, that depicts the part of the document. The DOM indicates the document as a logical tree of the node. It gives us various methods to alter the structure of the tree, create, update, or remove the existing nodes, or even add custom events or event listeners to the HTML elements.

Example of DOM:

Page Title

Welcome To GFG

Default code has been loaded into the Editor.

Tree representation for the above code:

Virtual DOM is a lightweight representation of the DOM of a webpage with the help of javascript objects. Every HTML element can be represented as its virtual DOM counterpart. For example:

HTML node:

Welcome To GFG

Virtual DOM node:

{ "tag": "h2", "children": { "text": "Welcome To GFG" } }

Some javascript libraries and frameworks, for instance, vue or react, use the concept of Virtual DOM to make any changes to the real DOM. This is because when the DOM is large and has many nodes present, the operation to change or update the DOM tree becomes very expensive. And so, in order to avoid this, VDOM came into the picture, as it helps us to only update that part of the real DOM which underwent any changes, keeping the rest of the real DOM intact.

How does Virtual DOM Works?

Vue.js uses a reconciliation technique to update the real DOM. With the help of various diff algorithms, vue.js determines whether virtual DOM differs from the real DOM, and then updates only that part of the real DOM that is different from the virtual DOM.

Example 1: This example describes the creation of a Virtual DOM in Vue.js.

HTML `

VueJS DOM Tree

GeeksforGeeks

This is VueJS DOM tree Example

`

DOM representation:

Output:

In the script tag, we create a new element, "h1", with content as "Hello World". We then insert the element inside the "div" tag with the id "app". Upon render, the Vue.js code returns the following HTML element:

Vue.js virtual DOM creates the corresponding HTML element on the real DOM:

Hello World

From the above example, we can see that the VDOM in vue.js extends the vue.js instance and is essentially composed of javascript objects.

Example 2: This example illustrates rendering the content by clicking the button.

HTML `

VueJS DOM Tree

GeeksforGeeks

Vue.js DOM tree

Click me

{{text}}

</div>
<script>
    new Vue({
        el: '#app',
        data: {
            text: ''
        },
        methods: {
            clickHandler() {
                this.text = 
    "Welcome to the GeeksforGeeks Learning"
            }
        },
    });
</script>

`

In the above code:

Output: