computed vs watch in Vue?In Vue 3, both computed and watch can react to reactive data changes. Which statement best describes when to use computed instead of watch?
Think about whether you want a value that updates automatically and is cached, or if you want to run code when data changes.
computed properties are for deriving and caching values based on reactive data. watch is for running side effects when data changes.
computed property?Given the following Vue 3 computed property, what will be the value of fullName.value after firstName.value = 'Jane'?
import { ref, computed } from 'vue'; const firstName = ref('John'); const lastName = ref('Doe'); const fullName = computed(() => `${firstName.value} ${lastName.value}`); firstName.value = 'Jane'; // What is fullName.value now?
Remember that computed properties update automatically when their dependencies change.
The computed property fullName depends on firstName and lastName. Changing firstName.value to 'Jane' updates fullName.value to 'Jane Doe'.
watch callback updates the watched reactive source?Consider this Vue 3 code snippet:
import { ref, watch } from 'vue';
const count = ref(0);
watch(count, (newVal, oldVal) => {
if (newVal < 3) {
count.value++;
}
});
count.value = 0;What will be the final value of count.value after this code runs?
Think about how watch triggers when the reactive source changes inside its own callback.
The watcher increments count.value while it is less than 3. It triggers again each time count.value changes, stopping when it reaches 3.
watch syntax correctly watches multiple reactive sources?Which option correctly watches two reactive refs a and b and runs a callback when either changes?
Check the Vue 3 docs for watching multiple sources syntax.
Option C uses an array of refs as the first argument, which is the correct way to watch multiple sources.
computed property not update when obj.count changes?Given this Vue 3 code:
import { reactive, computed } from 'vue';
const obj = reactive({ count: 0 });
const doubleCount = computed(() => obj.count * 2);
obj.count = 1;
// doubleCount.value is still 0. Why?Check the computed function syntax carefully.
The computed function must return a value. Without a return statement, it returns undefined and does not update.