Watchers are an often misunderstood feature in Vue.
Some developers use them all the time.
Some never use them.
And how exactly are they different from computed props and methods?
Here are a few rules of thumb that I use.
When in doubt, use a computed prop
This is my order of preference:
- Computed properties
Computed props have many benefits, so I try to use them everywhere. But not everything can be a computed prop :(
So that's when I'll use a watcher.
If that fails, you can always stick things into a method and call it directly.
The problem I've seen is that watchers can do anything a computed prop can, just not as well. So a watcher is used when a computed prop would have been the better choice.
Many watchers can be easily converted into computed props, and I'd highly recommend you to do this!
Don't expect to use them a lot
In my experience watchers are the least common way of organizing logic.
But this will likely vary widely. There are always many ways of accomplishing the same goal.
My components tend to have a lot of computed props, with a healthy dose of methods. You need methods for things like event handlers, so you can never really get away from them completely.
Occasionally I'll have a component with a few watchers in there.
But again, it depends.
Different projects, different applications, different programming styles. These will all affect what your component looks like.
Dealing with side effects
The perfect use case for watchers is dealing with side effects.
(at least in my opinion)
Side effects are responsible for a huge amount of the complexity in your application, so you want to reduce their effect as much as possible.
But you also can't get rid of them completely.
Without side effects your application wouldn't do anything interesting.
Side effects are anything that changes state outside of it's immediate scope. If you have a function that does some calculations and keeps track of the intermediate values, that's not a side effect.
However, if that function is updating the state of the entire component, now it becomes a side effect.
These side effects work really well when they're inside of a watcher. (I go into more detail on this)
Let's say you have a piece of state that you want to save to local storage.
You could call a method to save it every single time you modifiy that state, but that gets old pretty fast. And when you add a new feature, you'll have to remember to call that method to keep things in sync.
Using a watcher here is much more convenient.
The watcher is set up to fire whenever that piece of state is changed. When it's fired, it saves the piece of state to local storage.
Now if you add a new feature that modifies that state you don't have to do anything! The watcher automatically takes care of that for you.