← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 7 of 7

Deep watchers

A deep watcher notices changes to nested properties inside an object or array, not just when it is replaced.

In this page:

  1. Deep watchers
Syntax
markup
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

markup
<!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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not enabling deep for nested changes
  2. Deep watching huge objects
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.