Vuex 学习6 - 核心概念Module

Module

**教程来自Vuex官网:https://vuex.vuejs.org/zh/guide/modules.html技术胖https://www.jspang.com/**教程

模块组一般不用再项目较小的情况

由于使用单一状态数,医用的所有状态都会几种到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter,甚至是嵌套子模块——从上至下进行同样方式的分隔:

const moduleA = {
    state: { ... },
    mutations: { ... },
    actions: { ... },
    getters: { ... }
};
              
const moduleB = {
	state: { ... },
    mutations: { ... },
    actions: { ... },
};

const store = new Vuex.store({
	modules: {
    	a: moduleA,
        b: moduleB,
    }
});

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

模块的局部状态

对于模块内部的 mutation 和 getter,接受的第一个参数模块的局部状态对象

const moduleA = {
    state: { count: 0 },
    mutations: {
        add (state) {
            // 这里的 `state` 对象时模块的局部装填
            state.count++;
        }
    },
    
    getters: {
        doubleCount (state) {
            return state.count * 2;
        }
    }
}

同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

const moduleA = {
    // ...
    actions: {
        addIfOddOnRootSum ({ state, commit, rootState }) {
            if ((state.count + rootState.count) %2 === 1) {
                commit('add');
            }
        }
    }
}

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {
    // ...
    getters: {
        sumWithRootCount (state, getters, rootState ) {
            return state.count + rootState.count;
        }
    }
}

命名空间

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 做出响应。

如果你希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: ture 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:

const store = new Vuex.Store({
    modules: {
        account: {
            namespaced: true,
            // 模块内容(module asserts)
            state: {
                // ...
            },
            getters: {
                isAdmin() {
                    // ...
                } // -> getters['account/isAdmin']
            },
            actions: {
                login() {
                    // ...
                }// -> dispatch('account/login')
            },
            mutations: {
                login() {
                    // ...
                } // -> commit('account/login')
            }
        },
        // 嵌套模块
        modules: {
            // 继承父模块的命名空间
            myPage: {
                state: {
                    //...
                },
                getters: {
                    profile() {
                        //...
                    }// -> getters['account/profile']
                }
            },
            
            // 进一步嵌套命名空间
            posts: {
                namespaced: true,
                state: {
                    // ...
                },
                getters: {
                    popular() {
                        // ...
                    } // -> getters['accout/posts/popular']
                }
            }
        }
    }
})

启动了命名空间的 getter 和 action 会收到局部化的 getterdispatchcommit。换言之,你在使用模块内容(module assets) 时不需要在同一模块内部额外添加命名空间前缀。更改 namespaced 属性后不需要修改模块内的代码。

在带命名空间的模块内访问全局内容(Global Assets)

如果你希望使用全局 state 和 getter,rootStaterootGetters 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。

如需要在全局命名空间分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatchcommit 即可。

modules: {
    foo: {
        namespaced: true,
        getters: {
            // 在这个模块的 getter 中,`getters` 被局部花了,
            // 你可以使用 getter 的第四个参数来调用 `rootGetters`
            someGetter (state, getters, rootState, rootGetters) {
                getter.someOtherGetter; // -> 'foo/someOtherGetter'
                rootGetters.someOtherGetter; // -> 'someOhterGetter'
            },
            someOhterGetter.state => {
                // ...
            }
        },
        actions: {
            // 在这个模块中,dispatch 和 comiit 也被局部化
            // 它们可以接受 `root` 属性一访问根 dispatch 或 commit
            someAction ({ dispatch, commit, getters, rootGetters}) {
                getters.someGetter; // -> 'foo/someGetter'
                rootGetters.someGetter; // -> 'someGetter'
                dispatch('someOtherAction'); // -> 'foo/someOtherAction'
                dispatch('someOtherAction', null, { root: true }); //-> 'someOtherAction'
                commit('someMutation'); // -> 'foo/someMutation'
                commit('someMutation', null, { root: true}); // -> 'someMutation'
            },
            someOtherAction (ctx, payload) {
                // ...
            },
        }
    }
}

在带命名空间的模块注册全局 action

如需要在带命名空间的模块注册全局 action,你可以添加 root: ture,并将这个 action 的定义放在函数 handler 中。例如:

{
    actions: {
        someOtherAction ({dispatch}) {
            dispatch('someAction');
        }
    },
    modules: {
        foo: {
            namespaced: true,
            actions: {
                someAction: {
                    root: true,
                    handler (namespacedContext, payload) {
                        // ...
                    }
                }
            }
        }
    }
}

带命名空间的绑定函数

当使用 mapStatemapGettersmapActionmapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:

{
	computed: {
    	...mapState({
        	a: state => state.some.nested.module.a,
        	b: state => state.some.nested.module.a,
    	})
	},
    methods: {
        ...mapActions([
            'some/nested/module/foo', // -> this['some/nested/module/foo']
            'some/nested/module/bar',
        ])
    }
}

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:

computed: {
    ...mapState('some/nest/module', {
        a: state => state.a,
        b: state => state.b,
    })
},
methods: {
    ...mapActions('some/nested/module', [
        'foo', // -> this.foo()
        'bar', // -> this.bar()
    ])
}

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

// 注册模块 'myModule'
store.registerModule('myModule', {
    // ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
    // ...
})

之后就可以通过 store.state.myModulestore.state.nested.myModule 访问模块的状态。

模块动态注册功能使得其他 Vue 插件可以通过在 store 附加新模块的方式来使用 Vuex 状态管理。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的状态管理。

你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。这一,你不能使用此方法写在静态模块(即创建 store 声明时的模块)。

保留 state

在注册一个新的 module 是,你很有可能想保留过去的 state,例如从一个服务端渲染的应用保留 state。你可以通过 perserveState 选项将其归档:stote.registerModule('a', module, { perserveState: true})

当你设置 preserveState: true 时,该模块会被注册,action、mutation 和 getter 会被添加到 store 中,但是 state 不会。这里假设 store 的 state 已经包含了这个 module 的 state 并且你不希望将其覆写。

模块重用

有时我们可能需要创建一个模块的多个实例,例如:

如果我们使用一个纯对象来声明模块的状态,那么这个状态对象会通过引用被共享,导致状态对象被修改时 store 或模块间数据互相污染的问题。

实际上这和 Vue 组件内的 data 是同样的问题。因此解决办法也是相同的——使用一个函数来声明模块状态(仅 2.3.0+ 支持):

const MyReusableModule = {
  state () {
    return {
      foo: 'bar'
    }
  },
  // mutation, action 和 getter 等等...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值