admin管理员组

文章数量:1244224

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

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()
})
Share Improve this question asked Aug 23, 2017 at 17:16 ChrisChris 14.2k23 gold badges93 silver badges182 bronze badges 4
  • u might need to check vuex.vuejs/api/#watch – ctf0 Commented Nov 5, 2018 at 12:15
  • 2 No it will run for all mutations unfortunately: docs – Mike Harrison Commented Jan 8, 2019 at 13:10
  • How about using mapState in the ponent for just the particular data in your store state and then using a watch on that? – Ross Coundon Commented Mar 24, 2019 at 17:06
  • as @MikeHarrison mention in the docs and also as you can see in the vuex code github./vuejs/vuex/blob/dev/src/store.js (line 103). vuex just call any function in sub arrays without checking for mutation. so vuex actually not support it. of course you can go behind the secenes and build your own module/function which will handle it. and use it. – eli chen Commented Jun 21, 2019 at 5:36
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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.

Try something like this:

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

本文标签: javascriptvuex subscribe to individual mutationStack Overflow