How to Use Watchers in Vue.js Application
In this article, we are going to learn about Vue Watchers. Let get started:
Table of Contents
Watchers
A watcher is a special Vue.js feature that watches every change in the data properties. In short, watcher tracks value change of data variables.
Watcher syntax:
<script>
export default {
watch: {
}
}
</script>
We can watch any data variable in two ways.
Watch Method 1
We have to define our watcher inside the watch
property object. Have a look at the example:
<template>
<div id="app">
<h1>{{ count }}</h1>
<button @click="count += 1;">Increment</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
};
},
watch: {
count: function(value) {
// add your condition here
if (value === 3) {
// the value is 3 & do a task
}
}
}
};
</script>
Watch Method 2
The watch.name
optionally accept 2 parameters. The first value is new & the second value is the old value. Take a look at the example:
<template>
<div id="app">
<h1>{{ count }}</h1>
<button @click="count += 1;">Increment</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
};
},
watch: {
count: function(newValue, oldValue) {
console.log(newValue, oldValue)
}
}
};
</script>
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.