前言

  在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')
export default {
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。

写在最后

  以上就是本文的全部内容,希望给读者带来些许的帮助和进步,方便的话点个关注,小白的成长之路会持续更新一些工作中常见的问题和技术点。

 

最新文章

  1. centos6.5 lamp 环境 使用yum安装方法
  2. jQuery获取带点的id元素
  3. oracle 表被锁定 杀死进程
  4. ycsb-命令及参数-与生成的负载类型相关
  5. 校园导游之NABC个人分析
  6. HeadFirst 12 (web应用安全)
  7. Webservice 调用方式整理
  8. (转载)一句简单命令重启nginx - [nginx]
  9. 色情不是我的所有——在法律边缘起舞的 FC2
  10. 从文章"避免复制与粘贴"到文章"Extract Method"的反思(3)
  11. 【Java】关于并发
  12. PHP中的数组方法及访问方法总结
  13. zombie-phantom
  14. IP多播(组播)
  15. JS 精度问题处理
  16. 201521123110 《Java程序设计》第4周学习总结
  17. Harbor配置https认证
  18. 一起学Android之ViewPager
  19. ES6 箭头函数--特性
  20. Spring Cloud(Dalston.SR5)--Feign 声明式REST客户端

热门文章

  1. bitsadmin windwos自带下载命令
  2. python 发送POST请求
  3. FPGA驱动LCD显示红绿蓝彩条
  4. CodeForces Round #760 (Div. 3)
  5. JDBC如何解决乱码
  6. CAS 的问题 ?
  7. java-StringBuilder
  8. Maven的Scored介绍
  9. gateway聚合swagger3统一管理api文档
  10. 判断集合中存在String字符串 或 判断集合中不存在String字符串