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

例子

index.js

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

调用方法时应该在创建完实例之后的钩子中,未创建实例调用会找不到 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()); }

总结

  1. 当范围内使用动态方法注册 actions 时还是比较爽的,而且在destroyed 钩子中销毁可以节省一部分资源;
  2. 配置命名空间也可以避免覆盖问题,算是多一种手段吧(感觉还是应用在多模块,全局注册时用到这个);
  3. 当没有父子关系时,但还需要多页面共享状态,可以用动态注册就不太方便了;

(我好像还是没解决全局注册时方法过多的问题。。。)