前言

  在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。

写在最后

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

 

vue--vuex 中 Modules 详解的更多相关文章

  1. Vue组件通信方式全面详解

    vue组件通信方式全面详解 众所周知,Vue主要思想就是组件化开发.因为,在实际的项目开发中,肯定会以组件的开发模式进行.形如页面和页面之间需要通信一样,Vue 组件和组件之间肯定也需要互通有无.共享 ...

  2. Vue.js 数据绑定语法详解

    Vue.js 数据绑定语法详解 一.总结 一句话总结:Vue.js 的模板是基于 DOM 实现的.这意味着所有的 Vue.js 模板都是可解析的有效的 HTML,且通过一些特殊的特性做了增强.Vue ...

  3. vue2.0中router-link详解

    vue2.0中router-link详解:https://blog.csdn.net/lhjuejiang/article/details/81082090 在vue2.0中,原来的v-link指令已 ...

  4. winxp计算机管理中服务详解

    winxp计算机管理中服务详解01 http://blog.sina.com.cn/s/blog_60f923b50100efy9.html http://blog.sina.com.cn/s/blo ...

  5. cocos2dx常见的46中+22中动作详解

    cocos2dx常见的46中+22中动作详解 分类: iOS2013-10-16 00:44 1429人阅读 评论(0) 收藏 举报 bool HelloWorld::init(){    ///// ...

  6. Android中Context详解 ---- 你所不知道的Context

    转自:http://blog.csdn.net/qinjuning/article/details/7310620Android中Context详解 ---- 你所不知道的Context 大家好,  ...

  7. iOS中-Qutarz2D详解及使用

    在iOS中Qutarz2D 详解及使用 (一)初识 介绍 Quartz 2D是二维绘图引擎. 能完成的工作有: 绘制图形 : 线条\三角形\矩形\圆\弧等 绘制文字 绘制\生成图片(图像) 读取\生成 ...

  8. 【转】declare-styleable的使用(自定义控件) 以及declare-styleable中format详解

    原文网址:http://www.cnblogs.com/622698abc/p/3348692.html declare-styleable是给自定义控件添加自定义属性用的 1.首先,先写attrs. ...

  9. Python中dict详解

    from:http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html Python中dict详解 python3.0以上,pr ...

随机推荐

  1. 6月16日 Django作业 文件解压缩统计行数

    作业要求: 前端页面注意: 自己写的: from django.shortcuts import render, HttpResponse import zipfile import re # Cre ...

  2. Cobalt Strike的安装

    一.下载 压缩包下载回来之后,可以看到里面的文件有这些: 其中搭建团队服务器端的关键文件有两个,一个是cobaltstrike.jar,另一个是teamserver,这里我打算将团队服务器端搭在我的v ...

  3. onGUI常用脚本学习(引用)

    https://blog.csdn.net/Hannah1221/article/details/101941174?spm=1001.2101.3001.6650.3&utm_medium= ...

  4. Apache Tomcat如何高并发处理请求

    介绍 作为常用的http协议服务器,tomcat应用非常广泛.tomcat也是遵循Servelt协议的,Servelt协议可以让服务器与真实服务逻辑代码进行解耦.各自只需要关注Servlet协议即可. ...

  5. React优点?

    声明式, 组件化, 一次学习, 随处编写. 灵活, 丰富, 轻巧, 高效

  6. POI Excel索引是从0还是1开始??

    this.workbook.getSheetAt(1).getFirstRowNum() // == 0 this.workbook.getSheetAt(1).getLastRowNum() // ...

  7. 租户的概念和MybatisPlus实现

    租户的概念:https://baijiahao.baidu.com/s?id=1625945681925384464&wfr=spider&for=pc MybatisPlus框架的租 ...

  8. 一个 Spring Bean 定义 包含什么?

    一个Spring Bean 的定义包含容器必知的所有配置元数据,包括如何创建一个bean,它的生命周期详情及它的依赖.

  9. windows环境Jenkins配置与使用(springboot+war包+vue)

    一.后台发布 1.General配置 2.源码管理 3.构建触发器 4.构建环境 5.构建 clean install -Dmaven.test.skip=true -Ptest 6.Post Ste ...

  10. XMLBeanFactory ?

    最常用的就是 org.springframework.beans.factory.xml.XmlBeanFactory ,它 根据 XML 文件中的定义加载 beans.该容器从 XML 文件读取配置 ...