vuex 动态注册方法 registerModule的实现

2019-11-09,,

Vuex(2.3.0+)可以用store.registerModule方法在进入路由时进行注册,离开路由时候销毁 actions, mutations, getters, state,在一定范围内相同名称不会被覆写

例子

index.js

传this 的写法

module.exports = {
  install(_this) {
    _this.$store.registerModule(['abc'], {
      namespaced: true,
      state: {
        rightTest: 999
      },
      actions: {
        setTest: ({commit}, val) => {
          commit('putTest', val)
        }
      },
      mutations: {
        putTest: (state, val) => {
          state.rightTest = val;
        }
      }
    })
  },
  uninstall(_this) {
    _this.$store.unregisterModule(['abc'])
  }
};

不传this,有写 store 的写法

import store from '../../store';

export default {
  install() {
    store.registerModule(['abc'], {
      namespaced: true,
      state: {
        rightTest: 999
      },
      actions: {
        setTest: ({commit}, val) => {
          commit('putTest', val)
        }
      },
      mutations: {
        putTest: (state, val) => {
          state.rightTest = val;
        }
      }
    })
  },
  uninstall() {
    store.unregisterModule(['abc'])
  }
}

调用方法时应该在创建完实例之后的钩子中,未创建实例调用会找不到 store。

在install、uninstall时,传递this过去,可以在上面中直接调用。

dispath 时,如果设置了命名空间,则一定要加上,我这个因为没使用较复杂的命名,注册时的名字就在命名空间那用了。

test.vue

import abc from '../../store/test';
...
created() {
  // 挂载对应的 store
  abc.install(this);
  console.log(this.$store, 'install');
},
destroyed() {
  // 销毁对应的 store
  abc.uninstall(this);
  console.info(this.$store, 'uninstall');
},
methods: {
 test(){
  this.$store.dispatch('abc/setTest', Math.random());
 }

总结

当范围内使用动态方法注册 actions 时还是比较爽的,而且在destroyed 钩子中销毁可以节省一部分资源;

配置命名空间也可以避免覆盖问题,算是多一种手段吧(感觉还是应用在多模块,全局注册时用到这个);

当没有父子关系时,但还需要多页面共享状态,可以用动态注册就不太方便了;
(我好像还是没解决全局注册时方法过多的问题。。。)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • Vue组件间通信 Vuex的用法解析
  • 详解Vuex下Store的模块化拆分实践
  • Vuex 模块化使用详解
  • 详解vuex的简单todolist例子
  • vuex vue简单使用知识点总结

《vuex 动态注册方法 registerModule的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。