Performance: Watch vs computed decision
This affects how efficiently Vue updates the DOM and manages reactive data changes, impacting interaction responsiveness and rendering speed.
const derived = computed(() => props.value * 2);
watch(() => props.value, (newVal) => {
derived.value = newVal * 2;
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using computed for derived data | Minimal reactive updates | Single reflow per change | Low paint cost | [OK] Good |
| Using watch to update derived data manually | Multiple reactive updates | Multiple reflows possible | Higher paint cost | [X] Bad |
| Expensive operations inside computed | Blocks reactive updates | Blocks reflow | High paint cost | [X] Bad |
| Expensive operations inside watch | Runs after reactive update | May cause extra reflows | Moderate paint cost | [!] OK |
fullName in Vue 3 Composition API using computed?computed function takes a getter function and returns a reactive, cached value.watch is for side effects, reactive creates reactive objects, ref creates reactive primitives, none are for computed caching.count.value changes from 0 to 1?const count = ref(0);
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});
count.value = 1;count.value changes from 0 to 1, the callback logs the change with oldVal=0 and newVal=1.const count = ref(0);
watch(() => count, (newVal, oldVal) => {
console.log(newVal);
});
count.value = 5;count (a ref), but it should return count.value to watch the actual value.Pass the test and this pattern moves unknown