于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
如何使用module
在store文件夹下新建modules文件夹,并在下面建立moduleA.js和moduleB.js文件用来存放vuex的modules模块
moduleA.js文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const state = {
stateA:
'A'
}
const mutations = {
showA (state) {
return
state.stateA
}
}
const actions = {
showAAction (context) {
context.commit(
'showA'
)
}
}
const getters = {
getA (state) {
return
state.stateA
}
}
export
default
{state, mutations, actions, getters}
moduleB.js文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const state = {
stateB:
'B'
}
const mutations = {
showA (state) {
return
state.stateB
}
}
const actions = {
showAAction (context) {
context.commit(
'showB'
)
}
}
const getters = {
getA (state) {
return
state.stateB
}
}
export
default
{state, mutations, actions, getters}
store.js 文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import
Vue from
'vue'
import
Vuex from
'vuex'
import
state from
'./state'
import
mutations from
'./mutations'
import
getters from
'./getters'
import
actions from
'./actions'
import
moduleA from
'./modules/moduleA'
import
moduleB from
'./modules/moduleB'
Vue.use(Vuex)
const store =
new
Vuex.Store({
state,
mutations,
getters,
actions,
modules: {
moduleA,
moduleB
}
export
default
store
在组件中使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div
class
=
"modules"
>
<h1>{{moduleA}} --- {{moduleB}}</h1>
</div>
</template>
<script>
import
{ mapState } from
'vuex'
export
default
{
data () {
return
{}
},
computed: {
...mapState({
moduleA: state => state.moduleA.stateA,
moduleB: state => state.moduleB.stateB
})
}
}
</script>
模块动态注册
在 store 创建之后,你可以使用 store.registerModule 方法注册模块:
1
2
3
4
5
6
7
8
// 注册模块 `myModule`
store.registerModule(
'myModule'
, {
// ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule([
'nested'
,
'myModule'
], {
// ...
})
之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。模块动态注册功能使得其他 Vue 插件可以通过在 store 中附加新模块的方式来使用 Vuex 管理状态。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的路由状态管理。你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。