Skip to content
On this page

module

什么是 Module?

  • 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store 对象就有可 能变得相当臃肿;
  • 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module);
  • 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
javascript
const moduleA = {
    state:()=>({}),
    mutations: {},
    actions: {},
    getters: {}
}

const moduleB = {
    state:()=>({}),
    mutations: {},
    actions: {},
    getters: {}
}


const store = createStore({
    modules: {
        moduleA,
        moduleB
    }
})
store.state.a //.->moduleA 的状态
store.state.b//-->moduleB 的状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

module 的局部状态

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

module 的命名空间

默认情况下,模块内部的 action 和 mutation 仍然是注册在全局的命名空间中的:

  • 这样使得多个模块能够对同一个 action 或 mutation 作出响应;
  • Getter 同样也默认注册在全局命名空间;

如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块:

  • 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名;
javascript
const store = createStore({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      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['account/posts/popular']
          }
        }
      }
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

module 修改或派发根组件

javascript
// 这里一共有六个参数
changeNameAction({commit, dispatch, state,rootstate,getters, rootGetters}
commit("changeName","kobe");
ommit ("changeRootName"null, froot: true});
dispatch("changeRootNameAction"null, froot: true])
1
2
3
4
5
沪ICP备20006251号-1