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.
watch: {
searchText(newValue, oldValue) {
console.log(`changed from "${oldValue}" to "${newValue}"`);
}
}A first watcher
<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.
<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.
<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,
newValueandoldValueare 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:
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:
created() {
const stop = this.$watch('score', (val) => {
if (val >= 100) { console.log('You win!'); stop(); }
});
}Tip: Watchers declared in
watch(or withthis.$watch) are stopped automatically when the component is destroyed. Clear any timers you start, as the debounce example does withclearTimeout.
Test yourself
Which two arguments does a watcher handler receive?
- The event and the element
- The new value and the old value
- The component and the key
- Only the new value
You change user.address.city, but your watcher on user doesn't fire. What is missing?
immediate: trueflush: 'post'deep: true- A computed property
Which task is a good fit for a watcher rather than a computed property?
- Show the number of items in a cart
- Combine first and last name
- Send a search request after the query changes
- Format a price as
$9.99