How Does Virtual DOM Work in Vue.js?
What is Virtual DOM?
Virtual DOM is a lightweight copy of real DOM that allows Vue.js to efficiently update interface without directly interacting with real DOM on every data change.
How Does It Work?
- Vue creates virtual DOM representation (VNode) based on current data state.
- When data changes, new virtual tree (new VNode) is created.
- Vue compares old and new tree (diffing) and calculates minimal set of changes.
- Only changed part of real DOM is updated (patching), not entire interface.
Virtual DOM Advantages
- Performance — only changed part of interface is updated, not entire DOM.
- Development simplicity — Vue automatically optimizes updates.
- Reactivity — data changes are instantly reflected in interface without need to manually update DOM elements.
Virtual DOM Work Example in Vue
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
<template>
<p>Counter: {{ count }}</p>
<button @click="count++">Increment</button>
</template>
What Happens in This Code?
- Vue creates virtual DOM based on template (
template). - When button is clicked
countincreases. - Vue creates new virtual DOM and compares it with previous one.
- Vue finds difference (
diff) and changes only text in<p>, not entire document.
Virtual DOM makes Vue.js fast and convenient to work with. It minimizes real DOM updates, improving performance and making interfaces more responsive.