Performance: Virtual DOM and diffing mental model
This concept affects how quickly the page updates after user interaction by minimizing direct DOM changes.
<template>
<ul>
<li v-for="item in items" :key="item">{{ item }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const items = ref(['a', 'b', 'c']);
</script>const list = document.getElementById('list'); list.innerHTML = ''; items.forEach(item => { const li = document.createElement('li'); li.textContent = item; list.appendChild(li); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct DOM manipulation (clearing and rebuilding) | Many nodes removed and added | N reflows for N items | High paint cost | [X] Bad |
| Vue virtual DOM diffing with keys | Only changed nodes updated | Single reflow for changes | Low paint cost | [OK] Good |
count from 1 to 2?<template>
<div>
<p>Count: {{ count }}</p>
<button @click="count++">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(1)
</script>count variable changes from 1 to 2, affecting only the text inside <p>.<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, text: 'A' },
{ id: 2, text: 'B' }
])
// Later update
items.value = [
{ id: 2, text: 'B' },
{ id: 1, text: 'A' }
]
</script><template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, text: 'Apple' },
{ id: 2, text: 'Banana' },
{ id: 3, text: 'Cherry' }
])
// Later update
items.value = [
{ id: 1, text: 'Apple' },
{ id: 2, text: 'Blueberry' },
{ id: 4, text: 'Date' }
]
</script>Pass the test and this pattern moves unknown