Blog>
Snippets

Deep Watchers on Nested Data

Demonstrate how to set up a deep watcher on an object to detect nested property changes in Vue.js 3.
<template>
  <div>
    <input v-model="nestedData.innerProperty" placeholder="Change me">
    <p>Inner property value: {{ nestedData.innerProperty }}</p>
  </div>
</template>

<script>
  import { ref, watch } from 'vue';

  export default {
    setup() {
      const nestedData = ref({
        innerProperty: ''
      });

      watch(nestedData, (newVal, oldVal) => {
        console.log('Deep watch detected a change in nestedData:', newVal);
      }, { deep: true }); // setting the deep flag to true

      return { nestedData };
    }
  };
</script>
This Vue component consists of an input field bound to a nested property of an object using v-model. A deep watcher is set up on the `nestedData` object to detect changes to any of its nested properties. Deep flag is set to true in the watch options to ensure that the watcher is 'deep' and reactive to nested changes.
<style>
div {
  margin: 20px;
}

input {
  margin-top: 10px;
  padding: 5px;
  font-size: 16px;
}
</style>
CSS styles for the Vue component. It styles the div container and the input field to improve the user interface.