<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment">Count: {{ count }}</button> </template>
Vue uses a Virtual DOM to efficiently update the real DOM. When a reactive property changes, Vue creates a new Virtual DOM tree, compares it with the previous one (diffing), and applies only the minimal changes needed to the real DOM.
<script setup> import { reactive } from 'vue' const state = reactive({ count: 0 }) function updateCount() { // update count here } </script>
In Vue 3, reactive objects track property changes. Directly modifying a property like state.count += 1 triggers reactivity and Virtual DOM updates. Reassigning the whole object or mixing types breaks reactivity or causes errors.
<script setup> import { reactive } from 'vue' const state = reactive({ items: [] }) function addItem(item) { state.items.push(item) } </script> <template> <ul> <li v-for="item in state.items" :key="item">{{ item }}</li> </ul> <button @click="addItem('new')">Add</button> </template>
Vue uses keys in v-for to track elements. Using the item string as a key can cause issues if items repeat, preventing proper DOM updates. Keys must be unique and stable.
Keys allow Vue to track elements between renders. The diffing algorithm uses keys to find matching nodes and only moves or updates what changed, improving performance.
<script setup> import { reactive } from 'vue' const state = reactive({ items: ['a', 'b', 'c'] }) function update() { state.items.splice(1, 1, 'x') state.items.push('d') } </script> <template> <ul> <li v-for="item in state.items" :key="item">{{ item }}</li> </ul> <button @click="update">Update</button> </template>
Each click replaces the second item with 'x' and adds 'd' at the end. After two clicks, the list is ['a', 'x', 'c', 'd', 'd'].