admin管理员组

文章数量:1410705

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 mit a mutation to change the value of item, now I would like to know the new value of item in some other ponent, which one I should use? watch or subscribe?

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 mit a mutation to change the value of item, now I would like to know the new value of item in some other ponent, which one I should use? watch or subscribe?

Share Improve this question asked Mar 6, 2020 at 7:58 jet_choongjet_choong 4334 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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.

本文标签: javascriptDifference between Vuex store WATCH and SUBSCRIBEStack Overflow