We use computed properties to automatically calculate values based on other data. We use watch to run code when data changes, like reacting to changes with side effects.
Watch vs computed decision in Vue
import { ref, computed, watch } from 'vue'; const count = ref(0); // Computed property const double = computed(() => count.value * 2); // Watcher watch(count, (newVal, oldVal) => { console.log(`Count changed from ${oldVal} to ${newVal}`); });
computed returns a reactive value that updates automatically.
watch runs a function when the watched data changes, useful for side effects.
const message = ref('Hello'); const shout = computed(() => message.value.toUpperCase());
watch(message, (newVal, oldVal) => {
console.log(`Message changed from ${oldVal} to ${newVal}`);
});const count = ref(0); const doubleCount = computed(() => count.value * 2); watch(count, (newVal) => { if (newVal > 10) { alert('Count is greater than 10!'); } });
This Vue component shows a count and its double. Clicking the button increases count. The computed property updates doubleCount automatically. The watcher logs changes to count in the console.
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref, computed, watch } from 'vue';
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});
function increment() {
count.value++;
}
</script>Use computed when you want to derive and display data reactively.
Use watch when you want to perform side effects like API calls or logging after data changes.
Computed properties cache their results until dependencies change, making them efficient.
Computed is for reactive, cached values based on other data.
Watch is for running code when data changes, especially side effects.
Choose computed for display logic, watch for reacting to changes.