Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuex subscribe to individual mutation

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()
})
like image 914
Chris Avatar asked Aug 23 '17 17:08

Chris


People also ask

How do you call a mutation in Vuex?

In Vuex, mutations are synchronous transactions: store. commit('increment') // any state change that the "increment" mutation may cause // should be done at this moment. To handle asynchronous operations, let's introduce Actions.

Is pinia better than Vuex?

Compared to Vuex, Pinia provides a simpler API with less ceremony, offers Composition-API-style APIs, and most importantly, has solid type inference support when used with TypeScript.

What is subscribe in Vuex?

subscribe(handler, { prepend: true }) The subscribe method will return an unsubscribe function, which should be called when the subscription is no longer needed. For example, you might subscribe to a Vuex Module and unsubscribe when you unregister the module.


2 Answers

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.

like image 80
holmicz Avatar answered Sep 21 '22 21:09

holmicz


From vuex docs:

The handler is called after every mutation and receives the mutation descriptor and post-mutation state as arguments.

It will react to all mutations, So you only can implement with your own conditional.

like image 43
Bagaskara Avatar answered Sep 21 '22 21:09

Bagaskara