Vue 'watch' Option
Example
Using a watcher inside the watch
option to make it impossible to choose values between 20 and 70 with an <input type="range">
.
export default {
data() {
return {
rangeVal: 4
};
},
watch: {
rangeVal(val) {
if( val>20 && val<70) {
if(val<40){
this.rangeVal = 20;
}
else {
this.rangeVal = 70;
}
}
}
}
};
Run Example »
Definition and Usage
The watch
option is an object with all the watchers that are declared on the Vue instance.
A watcher is a function with the same name as a data property or a computed property. The watcher is called automatically whenever that property with the same name gets changed.
When a watcher is called, the new and the previous values are available as arguments to the watcher function.
A watcher can also be a dot-delimited path, such as tiger.weight
, so that the watcher is only called when the weight
property of the tiger
object is changed.
Note: Arrow functions should be avoided when declaring watchers because the Vue instance cannot be reached from inside such a function using the this
keyword.
When writing watchers using the object syntax (see the example below), these options are available:
Option | Description |
---|---|
handler | This is where the watch function is written. |
'method name' | A watcher can be set up to call a method by providing the method name as a string. |
deep | Default value is 'false'. If the watcher is deep, it also reacts to changes further down in the property the watcher is set up to watch. |
immediate | Default value is 'false'. Triggers the watcher immediately after it is created. The old value will be 'undefined' the first time the watcher is triggered when 'immediate' is set to 'true'. |
flush | Default value is 'pre'. Specify when to run the callback function relative to when the component is rendered. Possible values are 'pre', 'post' and 'sync'. Use this flush option with caution. |
onTrigger/onTrack | Used for debugging. Only works in development mode. |
Note: Watchers can also be created using the $watch()
method.
More Examples
Example
Using a watcher with the object syntax.
<template>
<h2>Example watch Option</h2>
<p>The 'rangeVal' watcher is written with the object syntax, with immediate: true, so that rangeVal is moved to '70' when the page first loads:</p>
<input type="range" v-model="rangeVal">
<p>rangeVal: <span>{{ rangeVal }}</span></p>
</template>
<script>
export default {
data() {
return {
rangeVal: 40
};
},
watch: {
rangeVal: {
handler(val) {
if (val > 20 && val < 70) {
if (val < 40) {
this.rangeVal = 20;
}
else {
this.rangeVal = 70;
}
}
},
immediate: true
}
}
};
</script>
<style>
span {
padding: 3px;
font-weight: bold;
font-family: 'Courier New', Courier, monospace;
background-color: lightgreen;
}
</style>
Run Example »
Related Pages
Vue Tutorial: Vue Watchers
Vue Tutorial: Vue v-model Directive
Vue Reference: Vue $watch() Method