Skip to content
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