简体   繁体   中英

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;
    },
}

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

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