Deep watchers
A deep watcher notices changes to nested properties inside an object or array, not just when it is replaced.
In this page:
Syntax
export default {
watch: {
objectProperty: {
handler(newValue) {
// react to nested changes
},
deep: true
}
}
}
Deep watchers
By default watching an object only fires when it is reassigned in Vue 3 options watchers on a whole object, so add deep: true to react to nested changes.
The immediate option runs the handler once right away. With the Composition API, watch on a reactive object is deep automatically, while a ref holding an object needs deep: true.
Note:
Deep watching large structures is costly; watch specific paths when you can.
Example: Deep 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="user.address.city = 'Paris'">Move</button>
<p>{{ user.address.city }} | changes: {{ changes }}</p>
</div>
<script>
Vue.createApp({
data() { return { user: { address: { city: "Rome" } }, changes: 0 }; },
watch: { user: { handler() { this.changes++; }, deep: true } },
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: MoveParis | changes: 1
console: Paris | changes: 1
-->
Live Example
Related Topics
Common Mistakes
- Not enabling deep for nested changes
- Deep watching huge objects
- Expecting old and new values to differ for mutated objects
Chapter Summary
- deep: true watches nested changes
- immediate runs the handler at once
- Costly on big objects
- Watch a specific path when possible
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: