Watchers
A watcher runs your code whenever a piece of data changes, which is useful for side effects like saving or fetching.
In this page:
Syntax
export default {
watch: {
property(newValue, oldValue) {
// react to the change
}
}
}
Watchers
The watch option maps a property name to a function receiving the new and old values. Watchers suit asynchronous or expensive reactions to change, while computed suits derived values. You can watch nested paths using quotes, such as "user.name".
Note:
Prefer computed when you just need a derived value.
Example: Watchers
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<button @click="q = 'vue'">Search vue</button>
<p>Query: {{ q }} | History: {{ history.join(", ") }}</p>
</div>
<script>
Vue.createApp({
data() { return { q: "", history: [] }; },
watch: { q(newVal, oldVal) { this.history.push(`"${oldVal}" -> "${newVal}"`); } },
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: Search vueQuery: vue | History: "" -> "vue"
console: Query: vue | History: "" -> "vue"
-->
Live Example
Related Topics
Common Mistakes
- Using a watcher where computed would do
- Forgetting the old value is available
- Creating infinite loops by changing the watched value
Chapter Summary
- watch reacts to changes
- Receives new and old values
- Good for side effects
- Computed is better for derived data
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: