Vuex变异订阅触发多次

问题描述 投票:0回答:1

我正在使用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

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的原因是因为有一个事件我只想专门运行到该组件。

任何想法,请帮忙吗?

vue.js vuex vue-cli
1个回答
0
投票

您的示例代码听listingapp.vuehome.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返回值的更改做出反应,并且回调会将新值和旧值作为参数接收。如果需要,您可以观看多个状态。
© www.soinside.com 2019 - 2024. All rights reserved.