简体   繁体   中英

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()
})

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.

could you tell please what the reason have subscribtion to the mutation if the only work of mutation is changing store:

[types.MUTATE_SET_ACTIVE_TICKER]: (state, payload) => {
state.activeTicker = payload
},

and then you can take the data from the store in the component directly:

this.$store.state.activeTicker

Try something like this:

this.$store.subscribe(mutation => {
                if (mutation.type === 'setData') {
//  do something here
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM