Vue 3
Computed & Watch
Derive values with computed and react to changes with watch.
By EZ4Code Team
computedwatchreactivity
Code
import { ref, computed, watch, watchEffect } from "vue";
const price = ref(100);
const qty = ref(2);
const total = computed(() => price.value * qty.value);
console.log(total.value); // 200
// Watch a specific source, runs lazily
watch(price, (newVal, oldVal) => {
console.log("price:", oldVal, "->", newVal);
});
// watchEffect auto-tracks dependencies, runs immediately
watchEffect(() => {
console.log("total is", total.value);
});Explanation
computed caches a derived value and only recomputes when its dependencies change. watch explicitly observes a source and fires a callback with old and new values, lazily. watchEffect runs immediately and auto-tracks every reactive dependency used inside it.
More Vue 3 Snippets
Single-File Component
Define a Vue 3 component with script setup, template, and scoped styles.
Composition API
Organize reactive state, computed, and lifecycle logic by feature.
Refs & Reactive
Choose between ref and reactive for reactive state.
Props & Emits
Declare inputs and events, and implement v-model on a component.
Lifecycle Hooks
Register lifecycle callbacks as composable functions.
Slots & Scoped Slots
Distribute content with default, named, and scoped slots.