Vue Watcher

Posted on  by admin

Have you ever been used vue js watch property? If you are not, then you are a right place. In this tutorial i will discuss about vue js watch property and we will compare it with computed property.

When we have some data that needs to change based on some other data, it is tempting to overuse watch.

When computed properties are more appropriate in many cases, there are sometimes when a custom watcher is necessary.

For this reason Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data in vue js.

You should know that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. In this vue watch object property example i will create a simple vue example.

We will create three text field containing km, meter and millimeter. When one field is changed then all the field data will be updated according to their corresponding value. See the below example:. Vue.js ships with the watch option just like the computed methods and data option.

Watchers offer a great way to respond to data changes in a given element. The watch option is also a very powerful tool for conducting form validation.

Vue.js enables developers to create forms in Vue applications just as they would with HTML5.

That means little to no additional skills are required to build forms in the Vue template section of any component with plain HTML.

This tutorial of vue watchers is suited for developers at all stages, including beginners.

  1. Below are a few things you should already have before going through this vue watchers tutorial.
  2. Node.js version 10.x and above installed (you can verify whether you have it by running the following command in your terminal/command prompt:node -v.
  3. Vue’s latest version installed globally on your machine. Vue CLI 3.0 installed on your machine.To do this, uninstall the old CLI version firstnpm uninstall -g vue-cliThen, install the new onenpm install -g @vue/cliDownload a Vue starter projectUnzip the downloaded projectNavigate into the unzipped file and run the command below to keep all the dependencies up to datenpm install.

To do this, uninstall the old CLI version firstnpm uninstall -g vue-cli. Then, install the new onenpm install -g @vue/cli. Download a Vue starter project.

Introduction to Vue.js Watch

Unzip the downloaded project. Navigate into the unzipped file and run the command below to keep all the dependencies up to datenpm install.

Throughout this tutorial, we’ll inspect our code with Vue devtools, a browser extension developers use to debug their Vue projects. You can filter components, select components right inside the UI, inspect the DOM, and filter inspected data.

The extension also ships with some cool switching tabs such as switch to Vuex, switch to components, switch to events, routing, performance, and settings. To illustrate how to use the Vue watch option to handle form vue input validation, we’ll build a “create a new account” form that will contain fields for the user to enter their email and password.

Above all, you should have already downloaded the canvas project. That is to say, open the project in your IDE, go into the component folder. After that, replace the content of your Test.vue file with the code block below.

To clarify, this creates the form with Vue input binding. So, you can see it in action in the browser using the Vue devtools extension.

For the email input, we only want users to enter valid emails like (e.g., “[email protected]”). Fortunately, there are JavaScript functions that can check for that. So, we’ll use the watch option to trigger the function for the vue input validation to be checked.

Password validation

Replace your template section with the code block below. We first added the span element, which will contain the prompts we’ll create later.

Then, added the msg array to store the values as the user types.

After that, copy the following code block into the script section.

Here we created vue watchers for the mail and bound it to the email data.

So, the vue watchers can execute the validate email function, which we wrote inside the methods, as changes occur in the data. After that, run the application in the dev server.

So it should behave like this:. We want to validate that the password is are least eight characters long.

If it contains fewer than eight characters, we’ll prompt the user to make it eight.

Replace the script section of the test.vue component with the code block below. Finally, save the changes in your IDE and run the application again.

It should behave like this:. To sum up, you should now know how to use the watch option to perform form validation in Vue.

What are vue watchers?

Above all, validation is crucial when building forms. Likewise the practical code illustrations in this tutorial should help you learn how to implement form validation in your Vue apps.

In case, you have any questions about vue watchers. Let’s CONTACT US.

If you’re considering Vue Js development services, you can explore more about us – ArrowHiTech. eCommerce Reactivity for Vuejs, vue methods vs watchers, vuejs, Vuejs 3, vuejs development, vuejs methods, watchers, watchers in vuejs, watchers vs vue methods, Web app development, web application, web application development, web developer, web development, website, website dedicated developer, website developer, website development, website/mobile app development.

In this Vue tutorial we learn how to watch data and computed properties with watchers and execute code in response to any changes.

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

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.

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.

What we’ll build

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. We want to alert the user that listening to a volume above 5 may damage their hearing. But we don’t want to display the alert message when the user is already above 5 and turning the volume down.

As mentioned earlier, Vue automatically gives us the previous value of the data property as well. We can use it to check if the new value is greater than the old value.

If so, the user is turning the volume up and only then do we display the alert. Let’s modify the example above and check ifnewValueis greater thanoldValue.

  1. The message will display when the number reaches 5.
  2. But if we go past and decrease it again, the message won’t show.
  3. 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.

  1. We’ll change the logic to use a watcher instead of a computed property.
  2. But, this is where we’ll run into some complications.
  3. A watcher can only monitor a single data property.
  4. To watch both the first and last names, we will need to use two watchers.
  5. 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.

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. 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. If we run the example in the browser and type a name, Vue will log the message with each keypress to the console.

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.

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. That is the default behavior for a watcher.

If we want it to run when the page loads, we need to set theimmediateoption of the watcher to true.

This also means we need to change the syntax of the watcher method. The method becomes an object with a function calledhandlerthat contains the watcher logic.

Alongside the handler we use theimmediateproperty with a value of true.

To demonstrate, let’s make the changes to our example. Now when we run the example in the browser, it will print the message to the console on the page load.

So if we did reach out to an actual API, it would be able to load the reviews for Spiderman when the page loads. Many times in an application, you will want to watch a value in a nested object. But by default, Vue doesn’t watch nested data properties and requires us to set thedeepoption of the watcher to true. As an example, let’s modify our film example from earlier to use a nested data property object.

We’ll also change the watcher and set itsdeepproperty to true.

If we run the example in the browser and type some data into the text fields, the console will show a message on each keypress. Vue allows us to have both thedeepandimmediateproperties active at the same time. It doesn’t matter in which order the properties are defined. As long as they exist, Vue can use them. Vue counts arrays as deeply nested. So when we’re working with an array, we also have to specify and set thedeepoption to true. As an example, let’s create an list of films in an array with the option to add more by clicking a button.

To keep things simple, we’ll use the Javascriptarray pushmethod directly in the click listener. When we press the button, the new film is added to the array and logged in the console.

Using Vue devtools

It’s worth it to note that if we add theimmediateproperty, it will display the list with default values only.

It will not add “Aquaman” to the array until the click event fires. If we run the example above, the array is displayed with the two initial values. The new value will only be added once we click the button and the click event fires.

You’re browsing the documentation for v2.x and earlier. For v3.x, click here. In-template expressions are very convenient, but they are meant for simple operations. Putting too much logic in your templates can make them bloated and hard to maintain.

At this point, the template is no longer simple and declarative. You have to look at it for a second before realizing that it displays message in reverse. The problem is made worse when you want to include the reversed message in your template more than once.

That’s why for any complex logic, you should use a computed property. Original message: "{{ message }}".

Computed reversed message: "{{ reversedMessage }}". Here we have declared a computed property reversedMessage.

The function we provided will be used as the getter function for the property vm.reversedMessage:. You can open the console and play with the example vm yourself. The value of vm.reversedMessage is always dependent on the value of vm.message. You can, the setter will be invoked and vm.firstName and vm.lastName will be updated accordingly.

While computed properties are more appropriate in most cases, there are times when a custom watcher is necessary. That’s why Vue provides a more generic way to react to data changes through the watch option.

This is most useful when you want to perform asynchronous or expensive operations in response to changing data. In this case, using the watch option allows us to perform an asynchronous operation (accessing an API), limit how often we perform that operation, and set intermediary states until we get a final answer.

None of that would be possible with a computed property. In addition to the watch option, you can also use the imperative vm.$watch API.

← Template SyntaxClass and Style Bindings →. Caught a mistake or want to contribute to the documentation?Edit this on GitHub!Deployed onNetlify . The following article provides an outline for Vue.js Watch. Vue.js is an easy-to-use web application framework that can be used to develop great interactive front-end applications.

Whenever there is any change in a particular property, a Vue watcher helps one to understand the component data. Vue.js has a special feature, i.e. Watcher, which helps one to keep track of a property of the component state and a function is run when the value of property changes.

Watcher makes a code very simple and fast as it takes care of any change in data.

Watchers are used to seeing the changes in the data occurring in the reactive properties.

It also supports different asynchronous options with the changing value. The syntax written above is used for using Vue.js watch in our application. There are many hooks provided to observe the properties in Vue.js. For adding some functionalities with the change, we can add a watch and apply different logics with the changing value. Different examples are mentioned below:. Vue.js Watch with Button to change the text. In the example below, the “Change the Content” button is used to change the content displayed at the bottom of the output screen.

  1. The text that appears at the bottom of the output screen changes randomly by pressing the “Change the Content” button. The files used to implement the code below are:.
  2. The image’s link is stated below:. Drag the mouse and Change the value of the box. Node JS Training Program (3 Courses, 7 Projects)3 Online Courses | 7 Hands-on Projects | 25+ Hours | Verifiable Certificate of Completion | Lifetime Access 4.5 (8,366 ratings).

Related Courses. Vue JS Training (1 Courses, 3 Project)JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes). In the example below, the rectangle location changes along the x-axis with the movement of the mouse. The files used to implement the code below are:. The image’s link is stated below:. On full screen, the output will seem as the below image. Vue.js Watch usage with Counter. In the example below, the value of the counter changes when the “You clicked here _ times” button is clicked, and also one can see the change in value when the “Rupees Spent” or “Points Earned” value is entered.

The files used to implement the code below are:. The image’s link is stated below:. On the basis of the above article, we saw the concept of the watch in Vue.js. We saw when and why we should use the watch in Vue.js.

The examples will help us in understanding the application of watch in Vue.js and how it can be used in different situations and logics.

This is a guide to Vue.js Watch. Here we discuss the introduction, working of watch property in Vue.js and examples, respectively.

You may also have a look at the following articles to learn more –.

After dep.depend(), it checks if childOb is existed. The childOb is deinfed before Object.defineProperty is called.

The shallow is last parameter of defineReactive. In Observer class, it doesn't use this parameter. Thus, !shallow is true and it will start recursively observing the val. The Observe(val) returns an observer only if val is an Object or Array. For example, this.todo returns an Object. In this case, childOb eventually points to this.todo.__ob__.

Inside of the if block,

The dep of this.todo.__ob__ is collected as the dependent of current watcher. At this point, both the closure dep of this.todo and observer dep of this.todo.__ob__ is collected as the dependents.

Why are both dep collected for an Object?

The closure dep can only detect the change made directly on this.todo. For example:

However, if user wants to add a new property to this.todo, it has to rely on observer.dep to detect the change. This is what the doc(opens new window) tries to explain. We will cover this when we explain Vue.$set and Vue.$delete.

The childOb.dep is collected no matter whether the childOb is a plain object or an Array.In case the value is an Array, it needs to collect every item as dependent if the item is an object.

dependArray goes through each item of the array. In case the item has observer, it is collected as dependent - e.__ob__.dep.depend(). If the item is an array, it recursively calls dependArray.

These are all reactiveGetter does. We can see it primary functionality is collecting the dependents. On the other side, reactiveSetter notify the watcher that something has changed.

How to watch nested objects with deep

When the property of object or item in an Array is changed, the setter shold notify the watcher.

First, it gets the value. This is the old value. The new value is passed as the parameter - newVal.If the newVal is strictly equal to value, the setter directly returns. So, setting the same value won't notify the watcher.

Let's see the second condition.

Looks weried? If you know NaN is the only value that doesn't equal to itself in Javascript, then this would make sense. If you don't, please check this article(opens new window). This condition is used for checking whether the newVal and val are both NaN. If yes, the setter directly returns.

Next, the customSetter is called when the environment isn't the production environment. It is the forth parameter of defineReactive.It is used in initProps.

If the condition is met, the customSetter prints out the famous prop shouldn't be changed warning message. About the condition, you can ignore it for now. We will explain it in later chapter.

This comment(opens new window) explains this code very well.

If the property has the setter defined, then the setter is called with newVal. Otherwise, setting the newVal to val.

The setter set the childOb if the newVal is an object.The last statement of setter is calling notify on dep.

The notify is defined on the Dep. It is not very complicated.

As we explained before, the dep.subs saves all the watchers of dep.

If the environment is not a production environment and the config.async is falsy, then sort the watchers in the deps.subs as ascending order.If you have question about why the dep.subs is sorted only when the config.async is falsy, you can refer to this issue(opens new window).

Finally, the notify goes through dep.subs and call update on each watcher. This tells each watcher who is watching this dependent to update.

Let's look at the update on the watcher.

If the watcher is lazy, only set dirty as true. You might remember that the computed property is lazy. And, this is what lazy really means. When the computed property needs to update, instead of re-computing itself, it just sets dirty to true. During next evaluation of computed watcher, the new value will be calcualted.

If the watcher is set to sync, then directly call run method. Othewise, which by defualt asynchonorously update, it saves the current watcher to a queue by queueWatcher(this).

So far, the reactivy system finishes the entire cycle of reacting to a change.

Next, let's see how the watcher is updated.