In this article, we will be discussing watchers, one of the core concepts in Vue.js.
Watchers, just as the name implies are used to watch out for changes in a property previously defined in the data object. It is triggered whenever the value of that property changes.
Let's create a watcher for an "answer" property below. The watcher must have the same name as the property being observed.
export default {
data() {
return { answer: '' }
},
watch: {
answer: function()
{ console.log(this.answer)
}
},
}
The Watcher above will log the answer
property to the console anytime its value changes.
We can also access the old property value and new property value in a Watcher by adding two optional parameters as shown below.
export default {
data() {
return { answer: '' }
},
watch: {
answer: function(oldAnswer, newAnswer) {
console.log(`answer has been changed from ${oldAnswer} to ${newAnswer}`)
}
},
}
If we want to monitor the changes of items within an array or the properties of an object we use deep
. Let's watch out for changes in the person
Object below.
export default {
data() {
return {
person: { name: 'Linda', gender: 'Female', signedIn: false }
}
},
watch: {
person: {
deep: true, // Vue now watches for changes in the person Object
handler() { if (this.person.isSignedIn) this.records++ }
}
},
}
As a practical example, I have created a simple "App" where we use a Watcher to monitor the number of times a user has signed.