Watchers, as the name indicates, allow you to monitor data or computed property and execute a series of code in response to changes in the value of the data. Watchers and computed property have a lot of similarities in its usage with the difference being that watchers provide a generic way to react to data changes.
For this tutorial, we will scratch the surface on the use of Watchers in Vue.
Prerequisite
The reader must have a working knowledge of the Vue framework in Javascript.
Aim
We want to implement a volume tracker to:
- Check the current volume level
- Track Increases or decreases in the volume level
- Send an alert when the volume exceeds sixteen
Creating a Vue.js Application
We will start by creating a new Vue.js project. First off, we will head to our code editor, and within the terminal, we will install the Vue CLI (command-line interface) using the command below:
npm install -g @vue/cli
After we have completed the installation, we will proceed to create a new project folder using the command:
vue create projectname
Next, go into the directory using cd projectname and type the command:
npm run serve
Our default Vue homepage is as below:
Creating the Volume Tracker
For this project, we want to work with a clean template; thus, we will clear out the content in the App.vue file and replace it with the code below:
<template> </template> <script> export default { name: 'App', data(){ return{} }, methods: {}, computed: {}, } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
First, we want to create the user interface for our volume checker. Thus, in our template tag, we will add an h2, h3 and 2 button tags.
<h2>Volume Tracker (0-20)</h2> <h3> Current Volume - {{ volume }}</h3> <div> <button @click="volume +=2">Increase</button> <button @click="volume -=2">Decrease</button> </div>
In our script tag, we want to define a data property called volume and initialize it to zero.
data(){ return{ volume: 0, }
Now, when we click the increase button, the volume increases by two. Also, when we click the decrease button, the volume reduces by two.
We want to add a warning message to prompt back if the volume gets to sixteen. Here is where watchers come in as it assists us in watching the volume data property, and if it reaches 16, it will send an alert back.
Let us get on with the implementation of our code. Our script tag has the default export object, which contains the data, methods, and computed property. This object can also include a property which is the watch property.
The watch property is an object which contains keys that correspond with the data or computed properties we want to watch when its value changes. In this case, we want to watch the volume property, and we do this by assigning each key a function that executes once the property’s value changes.
(Note: the function automatically receives the updated value as an argument.)
We will add the code below to our script tag to show the use of the watch property:
watch: { volume(newValue){ if (newValue === 16){ alert("High Volumes can lead to hearing loss") } } },
Now, we reload our localhost, and once we increase the volume to 16, we will get our alert prompt. As you acknowledge the alert, the volume automatically increments to 16. This example is a basic explanation of how the watch property works when we change a value.
Here is how it looks:
Alternatively, decreasing the volume from a number greater than sixteen shows our alert once it gets to sixteen. From a user standpoint, getting a prompt when reducing a volume is not logical. Thus, let us fix this issue.
To do this, we will head back to the watch property and create a second argument called oldValue. This argument will help us check if we are increasing the volume. Next, we will change the conditional statement to “if the newValue is greater than the oldValue, and newValue is equal to sixteen, acknowledge the prompt”.
Below is an implementation of the logic above:
watch: { volume(newValue, oldValue){ if (newValue > oldValue && newValue === 16){ alert("High Volumes can lead to hearing loss") } } },
We save the changes and head back to our browser, and our result will be as below:
Here is the full code for our App.vue file:
<template> <h2>Volume Tracker (0-20)</h2> <h3> Current Volume - {{ volume }}</h3> <div> <button @click="volume +=2">Increase</button> <button @click="volume -=2">Decrease</button> </div> </template> <script> export default { name: 'App', data(){ return{ volume: 0, } }, methods: {}, computed: {}, watch: { volume(newValue, oldValue){ if (newValue > oldValue && newValue === 16){ alert("High Volumes can lead to hearing loss") } } }, } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Watchers vs. Computed Properties
You might be wondering if you can use the watch property instead of the compute property. The answer is yes, as watchers only react to data changes in a more generic way.
Computed
Computed properties are only necessary for the situations below:
- When we want to compose new data from an existing data source
- It reduces the length of a variable. It means the computed property comes in handy when you need to access a deeply nested property in an object and bind it to the template.
Watchers
Watchers are necessary for the following situations below:
- To check if there is a change in the value of a property to perform a specific action.
Conclusion
This article is to help the reader understand the concept of watchers. In a web app, the everyday use case of watchers is when we have to call an API in response to a change in data. It also helps apply transitions as watchers give a start and end state.
Resources
Here is a resource to go over if you want to further improve your knowledge of watchers. Thanks for reading, and happy coding!