Vuejs Watcher

Posted on  by admin

How to watch arrays with deep

Modified2 years ago. I am trying to use Watchers in VueJS but having bit of a hard time wrapping my head around them. For example in this case i have set up a watch which checks for the tab i am on and if the tab changes it should reset the selected value back to an empty array. Now i have set the parameters as oldValue and newValue but i am not quite sure how will i use those. Check this codepen. Here is the Complete example:-. I am not quite sure how i will use that watch so if someone can help me with that, i sure would appreciate it.

22 gold badges44 silver badges1515 bronze badges.

Web development, programming languages, Software testing & others

export default {
watch: {
name: function() {
console.log(this.name)
}
}
}

Watchers

  • 1515 bronze badges. You're using a fat arrow function for activeTab, it needs to be a normal function or it doesn't have a proper reference to this.
  • Change to this:. Also, there's an issue with your code when you use the check all box.
  • As a good rule of thumb, all top level functions should be declared using function.
  • Only use => within the functions themselves when a nested function needs access to this.
  • 2020 gold badges7171 silver badges140140 bronze badges. 140140 bronze badges. In this Vue tutorial we learn how to watch data and computed properties with watchers and execute code in response to any changes.

Computed Properties

We cover how to watch deep objects and arrays, run watchers on page load and when to use watchers instead of computed properties.

When to use a Watcher vs a Computed Property

Watchers vs Computed Properties. If you want to follow along with the examples in this lesson, you will need an app generated by the Vue CLI.

If you already have one from the previous lesson, you can use it instead. A watcher allows us to monitor a piece of data, or computed property, and execute code in response to a change in that data.

Watchers are similar to computed propertiesbut their use cases are different.

Before we get into that however, let’s see how to use watchers.

We define a watcher as a function in thewatchoption of the component’s config object.

Vue requires the watcher method name to be the same as the data property we want to watch.








Application





A watcher has access to the most recent value (newValue) and the previous value (oldValue) of the data property.

It will monitor the data property and execute the logic in the watcher each time it receives a new value.

noteA watcher does not return any value. It only works on other data, we don’t use it like a regular method in the template.

To demonstrate, let’s create a counter example that increments or decrements a number when the user clicks a button.

We’ll use a watcher to check when the number gets to 5, then show an alert.



When we run the example and increment the number to 5, it shows the alert.

Although the example above works fine, there is a potential issue.



If the number is above 5 and we click the ‘Decrement’ button, it will display the console log message again when it comes back to 5.

Let’s imagine that the number is a volume control.

import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");

We want to alert the user that listening to a volume above 5 may damage their hearing.

Basic Example

But we don’t want to display the alert message when the user is already above 5 and turning the volume down.

Let’s modify the example above and check ifnewValueis greater thanoldValue. The message will display when the number reaches 5. But if we go past and decrease it again, the message won’t show. Because watchers and computed properties monitor changes in data, a question that often comes up is when to use which.

Watchers provide a more generic way to react to data than computed properties. So, technically we can use watchers instead of computed properties, but it’s not recommended.

To demonstrate, we will revisit our full name example from the lesson on computed properties.

In the example we have two input fields that take a first and last name from the user and store them into their respective data properties.

A computed property then combines the two names into a full name and displays it in a paragraph in the template.

We’ll change the logic to use a watcher instead of a computed property.

But, this is where we’ll run into some complications.

A watcher can only monitor a single data property.



To watch both the first and last names, we will need to use two watchers.

A watcher cannot return a value, so we will need another data property to store the concatenated names.



Keeping the rules above in mind, let’s modify the example.

If we run the example above in the browser, it works the same as the computed property example.

import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
new Vue({
el: '#app',
template: '',
components: { App }
})
console.log('Vue version: ' + Vue.version)

Even though this approach works, it’s not ideal to use in this situation.

More code increases development time. More code is harder to test and debug.

Example #3

It’s more difficult to read and see at a glance what is happening.

Now that we know more about the differences, we can answer the question: when do we actually use which? Use Computed Properties when:. You need to compose new data from more than one existing data sources.An example would be when we created a full name from the first and last name data properties.

You need to reduce the length of a variable.An example would be when we need to access a deeply nested property in an object and bind it to the View.

It will make our template less cluttered.

Use Watchers when:. You want to check if a data or computed property has changed to a specific value in order to know if you are ready to perform an action.An example would be when we displayed an alert once the number in our counter reached 5.

You have to call an API in response to a change in data.An example would be a user clicking a button to receive a new inspirational quote, or upcoming events in their area etc.

By default, a watcher will not run when a page first loads.

However, many times in an application you will want to display data from an API immediately.



As an example, let’s consider a film review application.

Until the user performs a search, we don’t know which film they want to see a review for.



So we want to show the most popular reviews of the latest film on the home page.

Let’s create a simplified version of such an application and simulate the API call with a console log.

import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
export const myMixin = {
data() {
return {
title: "Mixins are cool",
copyright: "All rights reserved. Product of super awesome people"
};
},
created: function() {
this.greetings();
},
methods: {
greetings: function() {
console.log("Howdy my good fellow!" + this.title);
}
}
};
new Vue({
mixins: [myMixin],
render: h => h(App)
}).$mount("#app");

If we run the example in the browser and type a name, Vue will log the message with each keypress to the console.

Conclusion

So everything works as expected. Now let’s add a default value to thefilmNamedata property. The idea here is that because we use thev-modeldirective, the default value we specify will show up in the input field. And because it’s in the input field, it should activate the watcher and print the message to the console.

How to watch nested objects with deep

If we run the example in the browser, the new default film name shows up in the input field. However, the console doesn’t display a message, indicating that the watcher didn’t activate.