In this article, we do a dive into the virtual dom in Vue.js 3, and how we can traverse it with the goal of finding a specific component (or what we will call a vnode - more on this soon).

Most of the time, you don’t need to think about how Vue internally represents your components. Some libraries do make sure of this though — one such library is Vue Test Utils and it’s findComponent function. Another such use case is the Vue DevTools, which show you the component hierarchy for your application, seen on the left hand side of this screenshot.

Image for post

Note: this is a technical article. While I will do my best to explain how everything works, the only real way to fully grasp this is to write your own code and console.log a lot, to see what’s really happening. This is often the nature of the type of recursive algorithm we will be writing.

An alternative would be to watch the accompanying screencast, will I will make free indefinitely. You can find the source code for this example here.

Image for post

Interested in advanced content for Vue.js 3? Check out my course and weekly screencasts on https://vuejs-course.com.

The Virtual DOM

For various reasons, one of which is performance, Vue keeps an internal representation of the component hierarchy. This is called a Virtual DOM (VDOM). When something changes (for example a prop) Vue will figure out if something needs to be updated, calculate the new representation, and finally, update the DOM. A trivial example might be:

It could be represented like this:

- div 
  - span (show: true) 
    - 'Visible'

So it would be HTMLDivElement -> HTMLSpanElement -> TextNode. If show becomes false, Vue would update it’s Virtual DOM:

- div 
  - span (show: false) 
    - 'Visible'

Then, finally, Vue would update the DOM, removing the <span>.

#vuejs-3 #recursion #virtual-dom #javascript #vuejs #vue

Diving into the Vue 3’s Virtual DOM
16.25 GEEK