Blog>
Snippets

VDOM Diffing Mechanics

Present a side-by-side comparison of two virtual DOM trees to visualize how Vue.js identifies the differences and selectively updates the real DOM.
<div id="app"></div>
HTML root element where Vue instance will mount
/* VDOM Tree 1 */
{
  tag: 'div',
  children: [
    { tag: 'h1', text: 'Hello World' },
    { tag: 'p', text: 'This is a paragraph.' }
  ]
}
First virtual DOM tree representation
/* VDOM Tree 2 */
{
  tag: 'div',
  children: [
    { tag: 'h1', text: 'Hello World' },
    { tag: 'p', text: 'This paragraph has changed.' }
  ]
}
Second virtual DOM tree representation after some changes
const app = new Vue({
  el: '#app',
  data: {
    message: 'This is a paragraph.'
  },
  template: `
    <div>
      <h1>Hello World</h1>
      <p>{{ message }}</p>
    </div>
  `,
  methods: {
    updateMessage() {
      this.message = 'This paragraph has changed.';
    }
  }
});
Vue.js instance with a method to simulate a VDOM change
setTimeout(() => {
  app.updateMessage();
}, 2000);
Simulate an update to Vue component causing the VDOM to update after a timeout
/* CSS Styles */
#app {
  font-family: Arial, sans-serif;
}
Basic CSS styling for the Vue app