Concept Flow - Watch vs computed decision
Start
Define reactive data
Computed property
Auto recalculates
Used in template
Update UI
Shows how reactive data triggers either computed properties or watch effects, leading to UI updates.
const count = ref(1) const double = computed(() => count.value * 2) watch(count, (newVal) => console.log('Count changed:', newVal)) count.value = 2
| Step | Action | count.value | double.value | Watch Triggered | Output |
|---|---|---|---|---|---|
| 1 | Initialize count=1 | 1 | 2 | No | |
| 2 | Read double.value | 1 | 2 | No | |
| 3 | Change count.value = 2 | 2 | 2 | Yes | Count changed: 2 |
| 4 | Read double.value after change | 2 | 4 | No |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| count.value | 1 | 2 | 2 |
| double.value | 2 | 2 | 4 |
| Watch Triggered | No | Yes | No |
Vue reactive data triggers updates. Computed properties auto-recalculate when dependencies change. Watch runs code on reactive data changes for side effects. Use computed for derived data, watch for reacting to changes. Computed is cached; watch runs every change. Choose based on need: value or side effect.
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