前言

  在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. python 实现批量md转word

    # qianxiao996精心制作 #博客地址:https://blog.csdn.net/qq_36374896 #md批量转word import os def auto_md_to_docx(f ...

  2. w3af漏扫的基本使用

    一.安装 apt安装 apt-get update apt-get install -y w3af 出现无法定位软件包 源码安装 sudo apt-get install git sudo apt-g ...

  3. 实现一个函数功能:sum(1,2,3,4..n)转化为 sum(1)(2)(3)(4)…(n)?

    // 使用柯里化 + 递归function curry ( fn ) {  var c = (...arg) => (fn.length === arg.length) ?           ...

  4. Correct the classpath of your application so that it contains a single, compatible version of org.springframework.util.Assert

    一.问题描述 今天启动springboot工程时,报上面的错误. 二.解决方法 加入如下pom: <dependency> <groupId>org.springframewo ...

  5. 请说出作用域public,private,protected,以及不写时的区别?

    这四个作用域的可见范围如下表所示.说明:如果在修饰的元素上面没有写任何访问修饰符,则表示friendly.作用域    当前类  同一package  子孙类   其他packagepublic    ...

  6. 本地连接MySQL云服务器步骤与解决方案

    云服务器:aliyun MySQL 版本:mysql8 第一步首先,检查云服务器的 网络与安全 -> 安全组 是否开放了(MySQL)3306端口 第二步,登陆云服务器上的MySQL,检查需要远 ...

  7. 通过pink构造简易部署脚本

    安装git        https://www.cnblogs.com/youxiu326/p/10540753.html 安装maven https://www.cnblogs.com/youxi ...

  8. mybatis-02-mapper生成器插件使用

    sb_mybatis <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...

  9. Leetcode刷题之链表增加头结点的前缀节点

    链表之增加头结点的前缀节点 在许多链表题中往往需要在题目给的头结点之前增加一个前缀节点 通常在删除链表和头结点需要交换时需要用到这一操作 因为增加这个节点就避免了对删除头结点这种特殊情况的特殊处理 而 ...

  10. vim的vimrc配置

    windows "# modified by Neoh set helplang=cn "使用中文帮助文档 set encoding=utf-8 "查看utf-8格式的帮 ...