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()
})
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With