TExcelTAD
Home › Vue › Vue Watchers

Vue Watchers

Computed properties derive values. Sometimes, however, you need to do something when data changes: save a draft, call an API, start an animation, write a log line, or validate input after the user stops typing. That is what watchers are for.

A watcher is a function that Vue calls whenever a specific piece of reactive data changes. It receives the new value and the old value.

js
watch: {
  searchText(newValue, oldValue) {
    console.log(`changed from "${oldValue}" to "${newValue}"`);
  }
}

A first watcher

html · try it yourself
<div id="app">
  <p>
    <button @click="volume = Math.max(0, volume - 10)">🔉</button>
    Volume: {{ volume }}
    <button @click="volume = Math.min(100, volume + 10)">🔊</button>
  </p>
  <p v-if="warning" style="color:#b91c1c">{{ warning }}</p>
</div>

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

  createApp({
    data: () => ({ volume: 50, warning: '' }),
    watch: {
      volume(newVal, oldVal) {
        console.log(`volume ${oldVal} → ${newVal}`);
        this.warning = newVal >= 90 ? 'Careful: listening at high volume can damage hearing.' : '';
      }
    }
  }).mount('#app');
</script>

The method name in watch must match the data property it watches.

Watchers vs computed properties

Question Use
"I need a value that depends on other values" computed
"When X changes, I need to do something" watch
Must return a value? computed: yes — watcher: no
Can be asynchronous (timers, fetch)? computed: no — watcher: yes

If you find yourself writing a watcher only to keep another data property in sync, a computed property is almost always simpler.

Asynchronous work: debounced search

A watcher can start asynchronous work. This example waits until the user stops typing for 500 ms, then "searches" (simulated with a timer), and shows a loading state in between.

html · try it yourself
<div id="app">
  <input v-model="query" placeholder="Search a city…">
  <p v-if="loading">Searching…</p>
  <ul v-else>
    <li v-for="c in results" :key="c">{{ c }}</li>
  </ul>
</div>

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

  const CITIES = ['Hanoi', 'Ho Chi Minh City', 'Hamburg', 'Helsinki', 'Tokyo', 'Toronto', 'Lisbon', 'Lima'];

  createApp({
    data: () => ({ query: '', results: [], loading: false, timer: null }),
    watch: {
      query(text) {
        clearTimeout(this.timer);
        if (!text) { this.results = []; this.loading = false; return; }
        this.loading = true;
        this.timer = setTimeout(() => {
          this.results = CITIES.filter(c => c.toLowerCase().startsWith(text.toLowerCase()));
          this.loading = false;
          console.log(`searched "${text}" → ${this.results.length} result(s)`);
        }, 500);
      }
    }
  }).mount('#app');
</script>

Deep watchers

By default a watcher on an object only fires when the whole object is replaced, not when one of its properties changes. Add deep: true to watch nested changes too. For that, write the watcher as an object with a handler.

html · try it yourself
<div id="app">
  <p><label>Theme: <select v-model="settings.theme"><option>light</option><option>dark</option></select></label></p>
  <p><label>Font size: <input type="number" v-model.number="settings.fontSize"></label></p>
  <p>Saved {{ saves }} time(s).</p>
</div>

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

  createApp({
    data: () => ({ settings: { theme: 'light', fontSize: 16 }, saves: 0 }),
    watch: {
      settings: {
        handler(value) {
          this.saves++;
          console.log('auto-save', JSON.stringify(value));
        },
        deep: true
      }
    }
  }).mount('#app');
</script>

Note: With a deep watcher on a mutated object, newValue and oldValue are the same object, because it was changed in place rather than replaced.

Watcher options

Option Meaning
deep: true Also fire on nested property changes
immediate: true Run the handler once right away when the component is created
once: true Run only for the first change, then stop (Vue 3.4+)
flush: 'post' Run after Vue has updated the DOM (useful if you need to read the new DOM)

You can also watch a nested path with a dotted string key:

js
watch: {
  'settings.theme'(theme) {
    document.body.className = theme;
  },
  userId: {
    handler(id) { this.loadUser(id); },
    immediate: true   // also load the first user on start
  }
}

Creating a watcher in code

this.$watch() creates a watcher at runtime and returns a function that stops it:

js
created() {
  const stop = this.$watch('score', (val) => {
    if (val >= 100) { console.log('You win!'); stop(); }
  });
}

Tip: Watchers declared in watch (or with this.$watch) are stopped automatically when the component is destroyed. Clear any timers you start, as the debounce example does with clearTimeout.

Test yourself

Which two arguments does a watcher handler receive?

  1. The event and the element
  2. The new value and the old value
  3. The component and the key
  4. Only the new value

You change user.address.city, but your watcher on user doesn't fire. What is missing?

  1. immediate: true
  2. flush: 'post'
  3. deep: true
  4. A computed property

Which task is a good fit for a watcher rather than a computed property?

  1. Show the number of items in a cart
  2. Combine first and last name
  3. Send a search request after the query changes
  4. Format a price as $9.99