Difference between Vuex store WATCH and SUBSCRIBE

Viewed 1199

What is the main difference between watch and subscribe and when I should use one over another? From Vuex official documentation, it seems both methods are doing the same thing and serving the same purpose, both methods have access to the state object.

I am now having a state like below:

item: (state: any) => state.item

I also have an action to commit a mutation to change the value of item, now I would like to know the new value of item in some other component, which one I should use? watch or subscribe?

1 Answers

In the case that you want to do something when the value of item changes, using watch would be sufficient.

However, if you want to know how item is changed specifically, you would want access to the mutation object (which includes the type of mutation, the payload, and so on). In that case, you can use subscribe.

One example can be that you mutate item in 2 or more mutations and you only want to know the value of item when mutation1 changed it.

Edit: I haven't tried this, but I think using subscribe will call your function every time anything in the store is mutated.

Related