Vue Js Deep Watchers:In Vue.js, watchers are used to watch for changes in a specific data property and perform some action when that property changes. Deep watchers are used when the data property being watched is an object or an array, and the watcher needs to detect changes in the nested properties of that object or array.
When a deep watcher is set up, Vue.js will recursively traverse the object or array being watched and set up watchers for each of its nested properties. This can be useful when you need to react to changes in a deeply nested object or array in your Vue.js application.
How can you ensure that the callback fires on all nested mutations when using a watcher?
To ensure that the callback fires on all nested mutations when using a watcher, you need to use a deep watcher. A deep watcher will traverse the object deeply and watch all nested properties for changes, triggering the callback function whenever any of these properties are mutated.
Vue Js Deep Watchers Example
<script type="module">
const app = Vue.createApp({
data() {
return {
items: [
{ name: 'Item 1', value: 1 },
{ name: 'Item 2', value: 2 },
{ name: 'Item 3', value: 3 }
],
selectedItem: { name: 'Item 1', value: 1 },
}
},
watch: {
selectedItem: {
handler: function (newVal, oldVal) {
console.log('items has changed!', newVal, oldVal)
},
deep: true
}
}
});
app.mount('#app');
</script>