Performance: Watchers for side effects
This affects interaction responsiveness and visual stability by triggering code when reactive data changes.
watch(() => largeReactiveObject, async (newVal) => { await nextTick(); requestIdleCallback(() => { updateDOM(newVal); }); }, { deep: true });
watch(() => largeReactiveObject, (newVal) => {
// heavy synchronous processing
for (let i = 0; i < 1000000; i++) {
// simulate expensive task
}
updateDOM(newVal);
}, { deep: true });| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous watcher work | Multiple DOM updates | Multiple reflows triggered | High paint cost due to blocking | [X] Bad |
| Deferred watcher side effects | Batched or deferred DOM updates | Single or no reflows during interaction | Low paint cost, smooth rendering | [OK] Good |
watch in Vue?watch doescount in Vue 3 Composition API?watch(() => count, callback) or watch(() => count.value, callback). Passing the ref directly watches the ref object, not its value.watch(count, ...) watches the ref object, not its value. watch({ count }, ...) passes an object, invalid. watch('count', ...) uses invalid string. watch(() => count, ...) watches the value returned by the function, which is the ref's value.count.value changes from 1 to 2?import { ref, watch } from 'vue'
const count = ref(1)
watch(() => count.value, (newVal, oldVal) => {
console.log(`Changed from ${oldVal} to ${newVal}`)
})
count.value = 2newVal and oldVal representing the new and previous values of the watched source.count.value is 1. When changed to 2, the watcher logs "Changed from 1 to 2".import { ref, watch } from 'vue'
const count = ref(0)
watch(count.value, (newVal) => {
console.log(newVal)
})watch(() => count.value, callback).count.value directly, which is incorrect. It should be watch(() => count.value, ...).user and run a side effect only when the user.name changes, ignoring other properties. Which watcher setup is correct?user.name, watch a function returning that property.user.name directly, triggering only on name changes. watch(user, (newUser) => { console.log('User changed:', newUser) }) watches whole object, triggering on any change. watch(() => user, (newUser) => { console.log('User changed:', newUser) }, { deep: true }) watches whole object deeply, also triggers on any change. watch('user.name', (newName) => { console.log('Name changed:', newName) }) uses a string, which is invalid in Vue 3 Composition API.Pass the test and this pattern moves unknown