Search code examples
vue.jsvuex

Vuex two commits in same action does not trigger watch


When I watch $store.stateA, the watch callback function for the following seems to not trigger.

stateA: false

muationA(state,val){
 state.stateA = val  
}

actionA({commit},val) {
  commit('mutationA', true)
  commit('mutationB', false) //take this out would trigger the watch callback
}

So what is the case here? the entire action callback need to finish before the watch functions are triggered?


Solution

  • As Nit mentioned, both mutations cancel each other since they are done synchronously. Read the "Reactivity in Depth" section of the doc for more info. In particular (emphasis mine):

    In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop “tick”, Vue flushes the queue and performs the actual (already de-duped) work.

    Other watcher solutions do work differently and are triggered right away when the value changes (e.g. Backbone.js). Vue does not work that way.