一、定义
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = createStore({
modules: {
a: moduleA,
b: moduleB
}
})
二、命名空间
// 默认情况下,模块内部的 getter、action 和 mutation 仍然是注册在全局命名空间的
// 通过添加 namespaced: true 的方式使其成为带命名空间的模块
// 此时,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名
modules: {
account: {
namespaced: true,
state: () => ({ msg: '' }), // -> store.account.msg
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},
三、带命名空间的辅助函数
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
})
...mapActions([
'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
])
// 将模块的空间名称字符串作为第一个参数传递给辅助函数
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
...mapActions('some/nested/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
// 使用createNamespacedHelpers创建基于某个命名空间辅助函数
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
...mapState({
a: state => state.a,
b: state => state.b
})
...mapActions([
'foo',
'bar'
])
四、模块的添加、删除、判断
// 在store创建之后,你可以使用 store.registerModule 方法注册模块
store.registerModule('myModule', {
// ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})
// 使用store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块
// 通过 store.hasModule(moduleName) 方法检查该模块是否已经被注册到store。嵌套模块应该以数组形式传递模块名