TExcelTAD
Home › Vue › Vue computed & watch

Vue computed & watch

You met computed properties and watchers as options. In the Composition API they are functions you import from vue and call inside setup(): computed(), watch() and watchEffect(). The ideas are the same — derived values are cached, side effects run when data changes — but the syntax is more flexible.

computed()

computed(getter) returns a read-only ref whose value is cached until a dependency changes. Read it with .value in JavaScript, and directly in the template.

html · try it yourself
<div id="app">
  <p>
    <label>Price <input type="number" v-model.number="price"></label>
    <label>Qty <input type="number" v-model.number="qty" min="0"></label>
  </p>
  <p>Subtotal: {{ subtotal.toFixed(2) }} | VAT 10%: {{ vat.toFixed(2) }} | <b>Total: {{ total.toFixed(2) }}</b></p>
  <p v-if="freeShipping">🚚 Free shipping!</p>
</div>

<script type="module">
  import { createApp, ref, computed } from 'vue';

  createApp({
    setup() {
      const price = ref(12.5);
      const qty = ref(2);

      const subtotal = computed(() => price.value * qty.value);
      const vat = computed(() => subtotal.value * 0.1);
      const total = computed(() => subtotal.value + vat.value);
      const freeShipping = computed(() => total.value >= 50);

      return { price, qty, subtotal, vat, total, freeShipping };
    }
  }).mount('#app');
</script>

A writable computed takes an object with get and set:

js
const fullName = computed({
  get: () => `${first.value} ${last.value}`,
  set: (v) => { [first.value, last.value] = v.split(' '); }
});

watch()

watch(source, callback, options?) runs the callback when the source changes. The source can be:

Source Example
A ref watch(query, (q) => …)
A getter function watch(() => user.age, (age) => …)
A reactive object (deep automatically) watch(settings, (s) => …)
An array of sources watch([a, b], ([newA, newB]) => …)
html · try it yourself
<div id="app">
  <p>
    <select v-model="from"><option>USD</option><option>EUR</option><option>JPY</option></select>
    →
    <select v-model="to"><option>USD</option><option>EUR</option><option>JPY</option></select>
  </p>
  <p><input type="number" v-model.number="amount"> {{ from }} = <b>{{ result }}</b> {{ to }}</p>
  <p><small>Rates "updated" {{ fetches }} time(s)</small></p>
</div>

<script type="module">
  import { createApp, ref, watch } from 'vue';

  const RATES = { USD: 1, EUR: 0.92, JPY: 151 };   // pretend these came from an API

  createApp({
    setup() {
      const from = ref('USD');
      const to = ref('EUR');
      const amount = ref(100);
      const result = ref('');
      const fetches = ref(0);

      // watch several sources at once; immediate runs it on start
      watch([from, to, amount], ([f, t, a], [oldF, oldT]) => {
        if (f !== oldF || t !== oldT) fetches.value++;
        result.value = (a / RATES[f] * RATES[t]).toFixed(2);
        console.log(`${a} ${f} → ${result.value} ${t}`);
      }, { immediate: true });

      return { from, to, amount, result, fetches };
    }
  }).mount('#app');
</script>

Note: To watch a single property of a reactive object, use a getter: watch(() => state.count, …). Writing watch(state.count, …) passes a plain number, which Vue can't watch.

watchEffect()

watchEffect(fn) runs fn immediately and tracks automatically whatever reactive data it reads. Whenever any of it changes, fn runs again. You don't list sources, and there is no old value.

html · try it yourself
<div id="app">
  <p><input v-model="title"> <input type="color" v-model="color"></p>
  <p>Look at the frame's tab title and border!</p>
</div>

<script type="module">
  import { createApp, ref, watchEffect } from 'vue';

  createApp({
    setup() {
      const title = ref('My Vue page');
      const color = ref('#42b883');

      watchEffect(() => {
        document.title = title.value;
        document.body.style.border = `6px solid ${color.value}`;
        console.log('effect ran:', title.value, color.value);
      });

      return { title, color };
    }
  }).mount('#app');
</script>
watch watchEffect
Sources Explicit Auto-detected from what the function reads
Runs immediately Only with { immediate: true } Always
Old value ✅ yes ❌ no
Good for Reacting to one specific change, comparing old/new Syncing several values to something external

Stopping, cleaning up and options

watch and watchEffect return a stop function. Watchers created synchronously in setup() stop automatically when the component unmounts.

When a watcher starts async work, stale results can arrive late. Vue 3.5's onWatcherCleanup() registers a clean-up that runs before the next run (or on stop):

html · try it yourself
<div id="app">
  <button v-for="id in [1, 2, 3]" :key="id" @click="userId = id">User {{ id }}</button>
  <p>{{ status }}</p>
</div>

<script type="module">
  import { createApp, ref, watch, onWatcherCleanup } from 'vue';

  const fakeFetchUser = (id) => new Promise(r => setTimeout(() => r({ id, name: ['Ana', 'Ben', 'Chi'][id - 1] }), 800));

  createApp({
    setup() {
      const userId = ref(1);
      const status = ref('');

      watch(userId, async (id) => {
        let cancelled = false;
        onWatcherCleanup(() => { cancelled = true; console.log('ignored stale request for', id); });
        status.value = `Loading user ${id}…`;
        const user = await fakeFetchUser(id);
        if (!cancelled) status.value = `Loaded: ${user.name}`;
      }, { immediate: true });

      return { userId, status };
    }
  }).mount('#app');
</script>

Click the buttons quickly: only the last request updates the text.

Option Effect
immediate: true Run once right away
deep: true (or a number for max depth, 3.5+) Watch nested changes of a ref/getter source
once: true Fire only once
flush: 'post' Run after DOM updates (watchPostEffect is the shortcut)

Tip: Prefer computed whenever you're calculating a value. Reach for watch/watchEffect only for side effects: requests, timers, logging, storage, DOM APIs.

Test yourself

How do you watch only state.count of a reactive object state?

  1. watch(state.count, cb)
  2. watch(() => state.count, cb)
  3. watch('state.count', cb)
  4. watchEffect(state.count, cb)

What does computed() return?

  1. A plain value
  2. A read-only ref
  3. A function you must call
  4. A Promise

Which statement about watchEffect is true?

  1. It needs an explicit list of sources
  2. It provides the old value
  3. It runs immediately and tracks whatever it reads
  4. It only runs on unmount