This content originally appeared on DEV Community and was authored by Linda
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!
This content originally appeared on DEV Community and was authored by Linda
Linda | Sciencx (2021-02-22T13:36:47+00:00) Introduction to Vue Watchers. Retrieved from https://www.scien.cx/2021/02/22/introduction-to-vue-watchers/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.