A core feature of Vue.js and a huge factor in its performance and scalability, is taking advantage of a Virtual Dom in order to efficiently update the real DOM when needed. This happens behind the scenes during the component template rendering phase that is explained below. But before we dive right in let’s see what the DOM actually is.
The Document Object Model (DOM) is an interface that treats an HTML document as a tree structure where each node is an object representing a part of the document. The DOM represents a document like a logical tree of nodes.
DOM methods allow programmatic access to the tree and allow us to change the structure, style or content of a document. Nodes can also have event handlers attached to them.
In a modern application, the DOM tree can be extremely big and have thousands of nodes. Searching and updating the DOM is a huge bottleneck in web application performance. This is the reason Virtual DOM is created.
Vue knows how to convert this Virtual node to a real DOM node. When virtual nodes start to change Vue compares the new and the old state and decides if the DOM needs to be updated. This process is called reconciliation. If a change is required only the associated DOM nodes will be altered with the rest of the tree to remain intact.
Now that we are familiar with the concepts of DOM and virtual DOM let’s dive into the actual template rendering process itself.
Component template rendering
Component template rendering has two steps
— Step 1 Compilation is when we compile our template to a render function
— Step 2 Running the render function that will create the Virtual DOM node which will end up on the DOM we will see in our browser
The first step only happens once and can be performed in the server for significant performance improvement. For prototyping, compilation can also be done on the client but Vue.js runtime compiler needs to be included.
The second step takes place on the client once during the component mounting lifecycle and each time the diffing algorithm decides that the template should be re-rendered.
Introduction to the DOM
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a…