首页 > 解决方案 > Vuex 变异订阅触发多次

问题描述

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

应用程序.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 的听众

家.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.jsvuexvue-cli

解决方案


您的示例代码监听了和的listing变化,但根据您的帖子,他们似乎对不同类型的变化感兴趣?app.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 的返回值的更改做出反应,并且回调接收新值和旧值作为参数。如果需要,您可以查看多个状态。

推荐阅读