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(`The 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 within 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.
That's all folks, See you next week!
Top comments (5)
Would be nice to add
immediate: true
. This way you can do something like this:immediate: true
means your handler will trigger when the component is mounted, and again when the property changes.Sweet!
Very interesting. This makes me think about remote logging of events...
This is old vue
Nice article! I didn’t know about the deep member.