【问题标题】:Vuex mutation subscription trigger multiple timesVuex 变异订阅触发多次
【发布时间】:2019-08-27 02:29:17
【问题描述】:

我正在使用 vue CLI,我创建了多个组件

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

然后我还有一个 home.vue 的监听器

home.vue

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

问题是当我执行this.$store.commit('listing',1); 这个this.$store.subscribe((mutation) => { 触发两次时,这是预期的行为,因为我从不同的文件中侦听了两次事件,有没有办法让它每个组件只触发一次?

我将突变侦听器称为home.vue 的原因是因为有一个事件我只想专门针对该组件运行。

【问题讨论】:

  • watch 不是订阅所有状态更改而只对少数情况做出反应,这里应该更好吗? app.vue 和 home.vue 都应该只关注他们感兴趣的状态变化。
  • @ArieXiao 你能给我看一些代码吗?
  • 当你说trigger only once per component时,这意味着两个订阅组件的两个触发器;但是您的评论表明,无论订阅多少,您都只需要一个触发器。当您只需要一个触发器时,为什么要订阅多个组件?
  • @tony19 我必须这样做,因为我有一些仅适用于该特定组件的操作。

标签: vue.js vuex vue-cli


【解决方案1】:

您的示例代码听了listing 更改app.vue 和home.vue,但根据您的帖子,他们似乎对不同类型的更改感兴趣?

正如评论的那样,watch 应该是更好的方法,如果您只对一些更改而不是所有商店的更改感兴趣。比如:


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

区别在于:

  • subscribe 回调将在商店发生突变时被调用(在您的情况下,这可能会浪费一些不必要的回调调用)。回调方法接收突变和更新的状态作为参数
  • watch 只会对其第一个参数中定义的 getter 返回值的更改做出反应,回调接收新值和旧值作为参数。如果需要,您可以查看多个状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2018-02-01
    • 2021-07-14
    相关资源
    最近更新 更多