By default, Vue’s watch property only watch for changes at the top level of the data object. If you want to watch for changes in nested properties, you need to use the deep option.

Here’s how you can use deep watching in Vue.js:

Code:

<template>
  <p>Item name: {{ item.name }}, Item quantity: {{ item.quantity }}</p>
  <button @click="increaseQuantity">Increase quantity</button>
</template>

<script>
export default {
  data() {
    return {
      item: {
        name: 'I Phone',
        quantity: 50
      }
    }
  },
  methods: {
    increaseQuantity() {
      this.item.quantity++;
    }
  },
  watch: {
    item: {
      handler(val){
        console.log(val);
      },
      deep: true
    }
  }
}
</script>

In the above example, When we click on the Increase Quantity button, It executes the increaseQuantity function and it increases the quantity of the item. As we used the deep option inside the item watcher, it will trigger the handler function and it will console the updated result.

If you are using composition api, then you can consider below example for the reference:

<template>
  <p>Item name: {{ item.name }}, Item quantity: {{ item.quantity }}</p>
  <button @click="increaseQuantity">Increase quantity</button>
</template>

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

const item = ref({
  name: "I Phone",
  quantity: 50
})

const increaseQuantity = () => {
  item.value.quantity++;
}

watch(
  () => item,
  (newVal) => {
    console.log(newVal.value);
  },
  { deep: true }
)

</script>

Support On Demand!

Vue