Search code examples
javascriptvue.jsvuejs2vuex

Vue.js "Watch" not firing on simple boolean value change


The "Watch" event isn't firing in a Vuex Store. This is pretty basic. It's no more complicated than the example in the help. Does Watch not work in a store?

(All the answers I could find were regarding Angular.)

-Thanks

in store.js

state: {
    warningSwitch : false,
}

(...)

watch: {
    warningSwitch: function (newState, oldState) {
        /* console.log(" Triggered "); */
        if(newState){
            this.showWarningNotice({title: "Oops", text:"Connection Lost"});
            return;
        } else {
            this.showInfoNotice({title: "Whew...", text:"Connected"});
        }
    }
},

(...)
mutations: {
    setWarningOn(state) {
        state.warningSwitchCounter++;
        state.warningSwitch = true;
    },
}

Solution

  • There is no such thing as a "watch" in a store, as Bert alluded to in the comments.

    There are two different approaches that you can take to simulate this behavior, depending on your needs and your architecture.

    One, you can watch the store's getters in your component and respond to it there:

    watch: {
        `$store.getters.warningSwitch`: function (newState, oldState) {
            /* console.log(" Triggered "); */
            if(newState){
                this.showWarningNotice({title: "Oops", text:"Connection Lost"});
                return;
            } else {
                this.showInfoNotice({title: "Whew...", text:"Connected"});
            }
        }
    },
    

    Two, you can actually dispatch additional behavior in the action of the store:

    actions: {
        setWarningOn: function(context, newState) {
            // broadcast event here or commit another mutation   
        }
    }