一、module的作用

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

二、module的使用方法

1、配置

  • 项目结构

  • 在index.js文件中进行组装
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 user from './modules/user'
import rights from './modules/right'
import roles from './modules/role'
import homes from './modules/home' Vue.use(Vuex); //组装模块并导出 store 的地方
export default new Vuex.Store({
//根节点相关
state,
mutations,
getters,
actions, //模块相关
modules: {
user,
rights,
roles,
homes, }, });
  • 在main.js的vue中进行注册store
import router from './router'
import store from './store/index' var vm = new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
});

2、使用

  • 以module文件夹中的user.js为例,如果建立的只是给固定的组件User组件使用,在user.js文件中使用命名空间
export default {

  namespaced: true,//使用命名空间,这样只在局部使用

  state: {

  },

  mutations: {

  },

  getters: {

}

}
  • 在User组件中发送ajax请求,注意携带命名空间的名称,也就是index.js组装时使用的名字
  created() {
this.getUsers()
},   methods:{ getUsers() {
//将token设置在请求头中提交,已经在拦截器中设置
// this.$http.defaults.headers.common['Authorization'] = localStorage.getItem("token");
this.$store.dispatch('user/getAllUserList', {_this: this, query: this.query})//this是Vue实例 }, }
  • 在user.js文件中的action进行异步操作
//有命名空间提交方式,类似this.$store.dispatch("user/getAllUserList");
actions: {
//将Vue实例进行传递接收
// getAllUserList(context, _this) {
// //局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState: //加入分页
getAllUserList(context, object) {
//局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState: //发送get请求获取API数据 crm/user?page=${context.state.page}&size=${context.state.size}&username=${object.query}
object._this.$http.get(`crm/user?page=${context.state.page}&size=${context.state.size}`)
.then((response) => {
// handle success
context.commit('GETALLUSER', response.data);
object._this.$message.success("获取数据成功")
object._this.page=1 })
.catch((error) => {
// handle error
console.log(error);
})
.finally(() => {
// always executed
});
// const response = await this.$http.get('crm/user');
// context.commit('GETALLUSER', response); },
}
  • 在user.js的mutations中进行state值得修改
mutations: {

    //action中提交该mutation
GETALLUSER(state, data) {
state.UserList = data.results; //将添加成功的数据添加到状态,用于页面更新
state.Total = data.count },
}

当然,在此之前state是需要初始化的:

  state: {

    UserList: [],
Total: null,
size: 2,
query: null,
page: 1,
}
  • 在getters中对state数据根据需求进行过滤
  getters: {
getUserList: state => { return state.UserList; }
}
  • 在User组件中通过computed方法获取getters
import {mapGetters} from 'vuex'

export default {
name: "User", computed: {
...mapGetters({ UserList: 'user/getUserList', }),
}
}

这样就可以在html中直接使用UserList属性了。

三、action、mutation、getters的互相调用

1、actions中调用其它action

    async delUser(context, object) {
//context包含的参数:commit,dispatch,getters,rootGetters,rootState,state
...
...
//删除后刷新页面
context.dispatch("getAllUserList", object._this) }
},

在action中通过context.dispatch方法进行调用

2、getters中调用其它gerter

getters:{

   getRolesList: state => {
return state.RoleList;
}, //调用其它getter
getRoleIdList: (state, getters) => {
let RoleIdArray = [];
getters.getRolesList.forEach(item => {
RoleIdArray.push(item.id);
});
return RoleIdArray
},
}

getters中可以传入第二个参数就是getters,然后通过这样使用其它getter。当然getters也可以传入根节点状态和getters。

 getters: {
// 在这个模块的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四个参数来调用 `rootGetters`
someGetter (state, getters, rootState, rootGetters) { }, },

3、组件中获取getters

(1)带上命名空间访问

 getters['user/getUserList']

(2)通过辅助函数访问(推荐)

  import {mapGetters} from 'vuex'

    computed: {

      ...mapGetters({
UserList: 'user/getUserList',
total: 'user/getTotal',
DeptList: 'user/geDeptList',
RoleList: 'user/getRolesList',
RoleIdList: 'user/getRoleIdList',
AllRoleList: 'user/getALLRolesList',
AllRoleIdList: 'user/getAllRoleIdList',
permissionDict: 'getPermission'
}), }

4、组件中提交action

this.$store.dispatch('user/setRole', {
_this: this,
id: this.currentuser.id,
rid_list: {roles: this.CheckedRolesIdList}
})

如果是全局的就不需要加上局部命名空间user

vuex之module的使用的更多相关文章

  1. vuex中module的命名空间概念

    vuex中module的命名空间概念 默认情况下,模块内部的 action.mutation 和 getter 是注册在全局命名空间的. 弊端1:不同模块中有相同命名的mutations.action ...

  2. vuex的module的简单实用方法

    当我们的项目越来越大的时候,我们就开始使用vuex来管理我们的项目的状态.但是如果vuex的状态多了呢,这个时候module就登场了.看了一下官方的文档,很详细,但是没有demo让初学者很头疼.那我就 ...

  3. Vuex基础-Module

    官方API地址:https://vuex.vuejs.org/zh/guide/modules.html 前面几节课写的user.js就称为一个module,这样做的原因是:由于使用单一状态树,应用的 ...

  4. [Vuex系列] - Module的用法(终篇)

    于使用单一状态树,应用的所有状态会集中到一个比较大的对象.当应用变得非常复杂时,store 对象就有可能变得相当臃肿.为了解决以上问题,Vuex 允许我们将 store 分割成模块(module).每 ...

  5. vuex之module

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象.当应用变得非常复杂时,store 对象就有可能变得相当臃肿. 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module) ...

  6. 深入理解Vuex 模块化(module)

    todo https://www.jb51.net/article/124618.htm

  7. 【mock】后端不来过夜半,闲敲mock落灯花 (mockjs+Vuex+Vue实战)

      mock的由来[假]   赵师秀:南宋时期的一位前端工程师 诗词背景:在一个梅雨纷纷的夜晚,正处于项目编码阶段,书童却带来消息:写后端的李秀才在几个时辰前就赶往临安度假去了,!此时手头仅有一个简单 ...

  8. Vuex、Flux、Redux、Redux-saga、Dva、MobX

    https://www.jqhtml.com/23003.html 这篇文章试着聊明白这一堆看起来挺复杂的东西.在聊之前,大家要始终记得一句话:一切前端概念,都是纸老虎. 不管是Vue,还是 Reac ...

  9. vuex分模块2

    深入理解Vuex 模块化(module) 转载  2017-09-26   作者:ClassName    我要评论 本篇文章主要介绍了Vuex 模块化(module),小编觉得挺不错的,现在分享给大 ...

随机推荐

  1. python 常用技巧 — 列表(list)

    目录: 1. 嵌套列表对应位置元素相加 (add the corresponding elements of nested list) 2. 多个列表对应位置相加(add the correspond ...

  2. vue 前后端数据交互问题解决

    先在vue项目中配置好路由组件路由 然后写相应组件 2 后端 写接口赔路由 第三  解决跨域问题 处理数据交互 这样前端就拿到了数据

  3. Ceph中PG和PGP的区别

    http://www.zphj1987.com/2016/10/19/Ceph%E4%B8%ADPG%E5%92%8CPGP%E7%9A%84%E5%8C%BA%E5%88%AB/ 一.前言 首先来一 ...

  4. mac 格式化U盘

    作者:Bailm链接:https://www.zhihu.com/question/27888608/answer/486347894来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...

  5. CPU的历史

    https://zhuanlan.zhihu.com/p/64537796 很多人都对电脑硬件有一点的了解,本人也算略懂一二,所以今天来为大家说说电脑的主要硬件之一––CPU(中央处理器). 那么我们 ...

  6. I2C自编设备驱动设计

    一.自编设备驱动模型 at24.c: static int __init at24_init(void) { io_limit = rounddown_pow_of_two(io_limit); re ...

  7. HTTP协议-Headers

    Request headers 1 Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 ...

  8. Another Blog

    I also hold a blog with thoughts of English learning. Get there ===>. It's a private blog. Actual ...

  9. VMware 虚拟机NAT模式如何设置网络连接,从头到尾全过程~!!

    一.首先查看自己的虚拟机服务有没有开启,选择电脑里面的服务查看: 1.计算机点击右键选择管理  2.进入管理选择VM开头的服务如果没有开启的话就右键开启  二.虚拟机服务开启后就查看本地网络虚拟机的网 ...

  10. leetcode上的位运算

    136-只出现过一次的数字 思路:可以考虑到数字以二进制形式存储,当两个不同的数字异或的时候会是true,所以把数组里的数字都一一处理一遍就可以了. class Solution { public: ...