前言
在Vue中State使用是单一状态树结构,应该的所有的状态都放在state里面,如果项目比较复杂,那state是一个很大的对象,store对象也将对变得非常大,难于管理。于是Vuex中就存在了另外一个核心概念 modules。本文就来总结 modules 相关知识点。
正文
1 、什么是模块Modules
Vuex允许我们将store分割成模块(Module), 而每个模块拥有自己的state、getters、mutation、action等,甚至是嵌套子模块——从上至下进行同样方式的分割。
const moduleA = {
state: ()=> ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB= {
state: ()=> ({ ... }),
mutations: { ... },
actions: { ... }
}
const store=new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})this.store.state.a// -> 获得moduleA 的状态this.store.state.b// -> 获得moduleB 的状态
内部state,模块内部的state是局部的,也就是模块私有的,
内部getter,mutation,action 仍然注册在全局命名空间内,这样使得多个模块能够对同一 mutation 或 action 作出响应。
2、模块内部参数问题
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象 state。
对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:
对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:
const moduleA = {
state: ()=> ({
count:"",
}),
actions: {//这里的state为局部状态,rootState为根节点状态 incrementIfOddOnRootSum ({ state, commit, rootState }) {if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
mutations: {// 这里的 `state` 对象是模块的局部状态 increment (state) {
state.count++
}
},
getters: {//这里的state为局部状态,rootState为根节点状态 doubleCount (state) {return state.count * 2
},
sumWithRootCount (state, getters, rootState) {return state.count + rootState.count
}
}
}
3、模块命名空间问题
(1)namespaced: true 使模块成为带命名空间的模块
当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
const store =new Vuex.Store({
modules: {
account: {
namespaced:true,// 模块内容(module assets) 在使用模块内容(module assets)时不需要在同一模块内额外添加空间名前缀。
state: () => ({}),// 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响 getters: {
isAdmin() {},// ->使用: getters['account/isAdmin'],// 你可以使用 getter 的第四个参数来调用 someGetter(state, getters, rootState, rootGetters) {// getters.isAdmin// rootGetters.someOtherGetter },
},
actions: {
login() {},// ->使用: dispatch('account/login')// 你可以使用 action 的第四个参数来调用//若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit 即可 someAction({ dispatch, commit, getters, rootGetters }) {// getters.isAdmin;// rootGetters.someGetter;// dispatch("someOtherAction");// dispatch("someOtherAction", null, { root: true });// commit("someMutation");// commit("someMutation", null, { root: true }); },
someOtherAction(ctx, payload) {},// 若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中。 otherAction: {
root:true,
handler(namespacedContext, payload) {},// -> 'someAction' },
},
mutations: {
login() {},// ->使用: commit('account/login') },// 嵌套模块 modules: {// 继承父模块的命名空间 myPage: {
state: ()=> ({}),
getters: {
profile() {},// -> 使用:getters['account/profile'] },
},// 进一步嵌套命名空间 posts: {
namespaced:true,
state: ()=> ({}),
getters: {
popular() {},// -> 使用:getters['account/posts/popular'] },
},
},
},
},
});
(2)带命名空间的绑定函数的使用
当使用 mapState, mapGetters, mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:
computed: {
...mapState({
a: state=> state.some.nested.module.a,
b: state=> state.some.nested.module.b
})
},
methods: {
...mapActions(['some/nested/module/foo',// -> this['some/nested/module/foo']()
'some/nested/module/bar'// -> this['some/nested/module/bar']() ])
}
createNamespacedHelpers 创建基于某个命名空间辅助函数,它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数。
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions }= createNamespacedHelpers('some/nested/module')
exportdefault {
computed: {// 在 `some/nested/module` 中查找 ...mapState({
a: state=> state.a,
b: state=> state.b
})
},
methods: {// 在 `some/nested/module` 中查找 ...mapActions(['foo','bar'
])
}
}
4、模块动态注册
在 store 创建之后,你可以使用 store.registerModule 方法注册模块
import Vuex from 'vuex'
const store=new Vuex.Store({/* 选项*/ })// 注册模块 `myModule`
store.registerModule('myModule', {// ... })// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {// ...
})
之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。
也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。
可以通过 store.hasModule(moduleName) 方法检查该模块是否已经被注册到 store。
写在最后
以上就是本文的全部内容,希望给读者带来些许的帮助和进步,方便的话点个关注,小白的成长之路会持续更新一些工作中常见的问题和技术点。