0
0
Vueframework~5 mins

Watch vs computed decision in Vue

Choose your learning style9 modes available
Introduction

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.

When you want to show a value that updates automatically based on other data.
When you need to perform an action or side effect after some data changes.
When you want to cache a value that depends on reactive data for better performance.
When you want to watch a specific data property and run code only when it changes.
When you want to transform data for display without extra code.
Syntax
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.

Examples
This computed property converts the message to uppercase automatically.
Vue
const message = ref('Hello');
const shout = computed(() => message.value.toUpperCase());
This watcher logs a message every time the message changes.
Vue
watch(message, (newVal, oldVal) => {
  console.log(`Message changed from ${oldVal} to ${newVal}`);
});
Computed calculates doubleCount, watcher alerts when count passes 10.
Vue
const count = ref(0);
const doubleCount = computed(() => count.value * 2);

watch(count, (newVal) => {
  if (newVal > 10) {
    alert('Count is greater than 10!');
  }
});
Sample Program

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.

Vue
<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>
OutputSuccess
Important Notes

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.

Summary

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.