简体   繁体   English

Vue.js“监视”未在简单的布尔值更改时触发

[英]Vue.js “Watch” not firing on simple boolean value change

The "Watch" event isn't firing in a Vuex Store. “监视”事件不在Vuex商店中触发。 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.) (我能找到的所有答案都是关于Angular的。)

-Thanks -谢谢

in store.js 在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. 正如伯特(Bert)在评论中所暗示的,商店中没有“手表”之类的东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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