一、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. Nginx的应用之动静分离

    Nginx 的动静分离 我们通过中间件将动态请求和静态请求进行分离,减少了不必要的请求消耗和延时. 动静分离后,即使动态服务不可用,但静态资源不会受到影响. 应用实例 1.准备环境 系统 角色 主机名 ...

  2. 一 shell编程

    好啦.从今天开始我们转入shell编程的行列.从鸟哥私房菜中,已经学到了一些shell编程的皮毛,这两个月打算系统的学习,学会,学熟练.加油吧 bash shell [root@localhost s ...

  3. Codeforces 1185G2 Playlist for Polycarp (hard version) 背包,暴力

    题意及思路:https://www.cnblogs.com/Als123/p/11061147.html 代码: #include <bits/stdc++.h> #define LL l ...

  4. day01 html介绍 文档声明头 head标签 body标签

    day01 html   初识html <!--文档的声明--> <!doctype html>   <html lang="en">    # ...

  5. PHP随机生成不重复的8位卡号(数字)和卡密(字符串)

    一.生成不重复的随机数字,可自定义长度(最多支持10位数) /** * 生成不重复的随机数字(不能超过10位数,否则while循环陷入死循环) * @param int $start 需要生成的数字开 ...

  6. linux(一)vi和vim

    vi 多模式文本编辑器 多模式产生的原因 四种模式 正常模式 插入模式 命令模式 可视模式 vi man vi vim vim正常模式 直接vim回车,或vim空格文件名回车 i进入插入模式 I(sh ...

  7. springcloud中provider-product依赖

    <dependencies> <dependency> <groupId>cn.lijun.springcloud</groupId> <arti ...

  8. SQL Server 2014 安装说明

    SQL Server 2014 安装说明 本节内容将说明如何通过安装向导在 Windows Server 2012 R2 上安装 SQL Server 2014. 先从 MSDN 网站上下载安装了 S ...

  9. Python基础教程(003)--Python的设计目标

    前言 了解Python的设计目标,这节是了解Python的背景,不需要掌握,但是需要你知道有这个东西.就是Python的目的是什么.作者开发这个Python语言的目的是什么. 知识点 一门简单直观的语 ...

  10. flask中的目录解析

    首先我们看一下博客blog的封面,flask和django都属于web框架.不过flask属于轻量级web框架,功能的实现是通过扩展实现的,extension.py 中存放各个对象,具体的功能通过对象 ...