Search code examples
vue.jsvuexvue-cli

Vuex mutation subscription trigger multiple times


I'm using vue CLI and I created multiple components

app.vue

import home_tpl from './home.vue';

new vue({
    el : '#app',
    components : { home_tpl },
    created(){
        this.$store.subscribe((mutation) => {
            switch(mutation.type){
                case 'listing':
                    alert();
                break;
        });
    }
})

and then I have also a listener to home.vue

home.vue

export default{
    created(){
        this.$store.subscribe((mutation) => {
            switch(mutation.type){
                case 'listing':
                    alert();
                break;
        });
    }
}

The problem is when I do this.$store.commit('listing',1); this this.$store.subscribe((mutation) => { trigger twice which is the expected behavior since I listen to the event twice from different file, is there a way to make it trigger once only per component?

The reason I call mutation listener to home.vue is that because there's an event that I want to run specifically to that component only.


Solution

  • You sample code listen to listing change for both app.vue and home.vue, but according to your posts, it seems they are interested in different kind of changes?

    As commented, watch should be a better approach if you are only interested in a few changes rather than all the changes of the store. Something like:

    
    // home.vue
    new vue({
        el : '#app',
        components : { home_tpl },
        created(){
            this.$store.watch((state, getters) => state.stateHomeIsInterested, (newVal, oldVal) => {
                alert()
            })
        }
    })
    
    // app.vue
    export default{
        created(){
            this.$store.watch((state, getters) => state.stateAppIsInterested, (newVal, oldVal) => {
                alert()
            })
        }
    }
    

    The difference is:

    • the subscribe callback will be called whenever there is a mutation in the store (in your case this may waste some unnecessary callback invocations). The callback method receives the mutation and the updated state as arguments
    • the watch will only react on the changes to the return value of the getter defined in its first argument, and the callback receives the new value and the old value as arguments. You can watch multiple states if required.