Computed Properties vs Watchers

💚 Vue.js Lesson 10 Intermediate

While both compute values based on state changes, Computed Properties are cached getters for rendering views, whereas Watchers run side effects in response to data mutations.

1 Computed Caching vs Watcher Side Effects

Choosing the correct tool ensures optimal rendering performance:

  • computed(): Declares a computed value that is cached based on its reactive dependencies. It only recalculates when its dependencies mutate, making it highly efficient. Use for formatting data or filtering lists.
  • watch() / watchEffect(): Runs a callback when a tracked variable changes. Use for asynchronous tasks (e.g. saving state to localStorage, making API requests in response to query changes).
2 Composition API Computed & Watchers

Let's check computed properties and watchers in a Composition API setup:

TypeScript — Computed & Watch
import { ref, computed, watch } from 'vue';

const query = ref('');
const products = ref([{ name: 'Laptop', price: 900 }, { name: 'Phone', price: 500 }]);

// 1. Cached computed list filter
const filteredProducts = computed(() => {
  console.log('Running computed filter...');
  return products.value.filter(p => p.name.toLowerCase().includes(query.value.toLowerCase()));
});

// 2. Watcher callback for side effects
watch(query, (newVal, oldVal) => {
  console.log('Query changed from:', oldVal, 'to:', newVal);
  // Run side effects here (e.g. save search queries history to database)
});
3 Code Challenge
Challenge: Write a component that tracks a numeric price state. Use a watcher to log a warning message to the console if the price value exceeds $100.