Vue Watch Data

Posted on  by admin

You have an array or an object as a prop, and you want your app to do something whenever that data changes.


So you create a watcher for that property, but Vue doesn't seem to fire the watcher when the nested data changes. Here's how you solve this. You need to set deep to true when watching an array or object so that Vue knows that it should watch the nested data for changes.

I'll go into more detail on what this looks like in this article, plus some other useful things to know when using watch in Vue. You can also check out the Vue docs on using watchers. First we'll do a quick refresher on what a watcher actually is.

Second, we have to take a slight detour and clarify the distinction between computed props and watchers.


Thirdly, we'll dive into how you can watch nested data in arrays and objects.

Feel free to skip straight here if you need — you can always come back to the first sections later on.

We'll also go through what you can do with immediate and handler fields on your watchers.

This will take your watcher skills to the next level! In Vue we can watch for when a property changes, and then do something in response to that change. For example, if the prop colour changes, we can decide to log something to the console:.

These watchers let us do all sorts of useful things. But many times we use a watcher when all we needed was a computed prop. Watched props can often be confused with computed properties, because they operate in a similar way.

It's even trickier to know when to use which one. But I've come up with a good rule of thumb. Watch is for side effects.

Introduction to the Watch API

If you need to change state you want to use a computed prop instead. A side effect is anything that happens outside of your component, or anything asynchronous. Common examples are:. Manipulating the DOM. Using a browser API, such as local storage or audio playback. None of these things affect your component directly, so they are considered to be side effects.

If you aren't doing something like this, you'll probably want to use a computed prop.

Computed props are really good for when you need to update a calculation in response to something else changing.

However, there are cases where you might want to use a watcher to update something in your data. Sometimes it just doesn't make sense to make something a computed prop. If you have to update it from your