Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
October 26, 2023
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>