What's The Deal With Vue's Virtual DOM?

What's The Deal With Vue's Virtual DOM?

Many Javascript frameworks like Vue, React and Ember implement a “virtual DOM”.

While it sounds like something from a sci-fi, its main purpose is to increase the speed and efficiency of DOM updates. It offers some additional benefits as well.

Reminding ourselves what the DOM actually is

We tend think of the DOM as the HTML document it represents. But actually the DOM is a tree-like data structure that comes into existence once an HTML document has been parsed by the browser.

The browser paints the DOM to the screen and will repaint it in response to user actions (e.g. mouse clicks) and updates via its API from your Javascript scripts e.g. document.createElement.

It’s expensive to update the DOM

When we use Javascript to make a change to our page, the browser has to do some work to find the required DOM nodes and make the change e.g.

// #myId could be anywhere in the document, which may have thousands of nodes!
document.getElementById('myId').appendChild(myNewNode);

In modern apps there can be thousands of nodes in the DOM, and so updates can be computationally expensive. It’s inevitable that small, frequent updates will slow the page down.

What is a virtual DOM?

The DOM can be represented as a data structure in Javascript, too. Here is pseudo-code of how a DOM node could be represented:

read more

Vue.js Transitions

Vue.js Transitions

Transitions in Vue allow you to apply effects to elements when they are inserted, updated or removed from the DOM. For example, the classic fade:

The transition system has been a feature of Vue since the first version, but in version 2 there have been some changes, mainly that it is now completely component-based (which I think is much better…more on this later).

What transitions do

Transitions can be tricky to understand. Here’s what you need to know to get started:

  • The transition system can work with CSS (e.g. visual effects like fading) but can also be used with JS (e.g. transitioning data between different values).
  • CSS transitions work in conjunction with the CSS3 transition and animation features. The CSS does the actual transitioning, but Vue handles stuff like when to add/remove appropriate classes etc.

Example

Let’s say we want to fade an element in or out when it is added/removed from the DOM, just like in the GIF at the start of this story.

Thinking just about CSS for now, to get a fade effect we might do something like this:

.in {
  opacity: 1;
  transition: opacity .5s ease-in-out;
}
.out {
  opacity: 0;
}

When we want to see the element, we use thein class, when we don’t, we use the out class. We use the CSS3 transition rule to provide the fade effect.

read more