The Virtual DOM helps Vue update the screen quickly by only changing what really needs to change. Diffing is how Vue finds those changes by comparing old and new views.
0
0
Virtual DOM and diffing mental model in Vue
Introduction
When building interactive web pages that update often, like a chat app.
When you want smooth user experience without the whole page reloading.
When you have lists or tables that change dynamically and need fast updates.
When you want to write simple code but still have efficient updates behind the scenes.
Syntax
Vue
const vnode = h('tag', { props }, children) // Vue creates a virtual node (vnode) representing the UI element // Diffing compares old vnode and new vnode to find changes
The h function creates virtual nodes in Vue's render functions.
Diffing happens automatically inside Vue; you don't write it yourself.
Examples
Vue will see the text changed from 'Hello' to 'Hello World' and update only that text.
Vue
const oldVNode = h('div', { class: 'box' }, 'Hello') const newVNode = h('div', { class: 'box' }, 'Hello World')
Vue will update only the second list item text from 'Item 2' to 'Item 3'.
Vue
const oldVNode = h('ul', null, [h('li', null, 'Item 1'), h('li', null, 'Item 2')]) const newVNode = h('ul', null, [h('li', null, 'Item 1'), h('li', null, 'Item 3')])
Sample Program
This Vue component shows a message that changes when you click the button. Vue uses the Virtual DOM and diffing to update only the text inside the <p> tag, making the update fast and smooth.
Vue
<template>
<div>
<button @click="toggle">Toggle Message</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const showHello = ref(true)
const message = computed(() => showHello.value ? 'Hello Vue!' : 'Goodbye Vue!')
function toggle() {
showHello.value = !showHello.value
}
</script>OutputSuccess
Important Notes
Virtual DOM is a lightweight copy of the real DOM kept in memory.
Diffing compares old and new virtual DOM trees to find minimal changes.
This process helps Vue update the page efficiently without reloading everything.
Summary
Virtual DOM lets Vue update only what changed, not the whole page.
Diffing is how Vue finds those changes by comparing old and new views.
This makes your app faster and smoother for users.