Using watchers in VueJs
Watchers in VueJs are functions on the component instance that are executed when a change occurs on a data
property in the component.
How to use watchers in VueJS
All watcher functions are placed in an object named watch
on the component's instance. Basically they are methods and their names must be the same with the property name in the data
option of the component. So if we had a property age
on the data
property, the watcher function for age
would also have a name of age
.
Take a look at the snippet below
<div id="app">
<h2>Click the button</h2>
<p>{{age}}</p>
<button @click='changeAge'>Click me</button>
<p>{{alert}}</p>
</div>
The snippet above is a sample of the HTML for the demo.
new Vue({
el: "#app",
data: {
age: 19,
alert: ''
},
methods: {
changeAge(){
this.age++;
}
},
watch: {
age(){
this.alert = 'age changed!'
}
}
})
What's happening there? when the button is clicked, the onlick
handler is executed and the age
is increased by one, since we set a watcher on age
, the alert
message is now set with a value and the message displayed on the page.
Before and after the button was clicked
As you see from the screenshots above, when the button is clicked, the alert message is then displayed.
Parameters in watcher functions
Wacther functions can be set with two parameters which arguments are passed to when being executed:
- The new value of the property being watched.
- The previous value of the property being watched.
Take a look at the snippet below:
<template>
<div>
<h2>Click the button</h2>
<p>{{age}}</p>
<button @click='changeAge'>Click me</button>
<p>{{alert}}</p>
</div>
</template>
<script>
export default {
data(){
return {
age: 19,
alert: ''
}
},
methods: {
changeAge(){
this.age++;
}
},
watch: {
age(newAge, oldAge){
this.alert = `age changed! to ${newAge} from ${oldAge}`
}
}
})
</script>
From the code above, the app would look like this now:
Warning!
Only use watchers for expensive actions, for simple actions like updating another data property based on the new value of another, use a [computed setter](vuejs.org/v2/guide/computed.html#Computed-S.. "computed setters").