vuex subscribe to individual mutation

Chris picture Chris · Aug 23, 2017 · Viewed 7.4k times · Source

Is it possible to subscribe to an individual mutation?

Instead of:

this.$store.subscribe((mutation, state) => {
   if(mutation === 'someMutation'){
       doSomething()
   }
})

I would like something like this:

this.$store.subscribe('someMutation', state => {
    doSomething()
})

Answer

holmicz picture holmicz · Jul 14, 2019

How about wrapping the method you have somewhere in Vue prototype?

So instead of having:

this.$store.subscribe((mutation, state) => {
   if(mutation === 'someMutation'){
       doSomething()
   }
})

You would have something like:

Vue.prototype.subscribeMutation = function(someMutation, someFunction) {
       this.$store.subscribe((mutation, state) => {
       if(mutation === someMutation){
           someFunction(state)
       }
    })
}

I haven't tested the code, but you should be able to get the working result easily.