vuex之module的使用
一、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的使用的更多相关文章
- vuex中module的命名空间概念
vuex中module的命名空间概念 默认情况下,模块内部的 action.mutation 和 getter 是注册在全局命名空间的. 弊端1:不同模块中有相同命名的mutations.action ...
- vuex的module的简单实用方法
当我们的项目越来越大的时候,我们就开始使用vuex来管理我们的项目的状态.但是如果vuex的状态多了呢,这个时候module就登场了.看了一下官方的文档,很详细,但是没有demo让初学者很头疼.那我就 ...
- Vuex基础-Module
官方API地址:https://vuex.vuejs.org/zh/guide/modules.html 前面几节课写的user.js就称为一个module,这样做的原因是:由于使用单一状态树,应用的 ...
- [Vuex系列] - Module的用法(终篇)
于使用单一状态树,应用的所有状态会集中到一个比较大的对象.当应用变得非常复杂时,store 对象就有可能变得相当臃肿.为了解决以上问题,Vuex 允许我们将 store 分割成模块(module).每 ...
- vuex之module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象.当应用变得非常复杂时,store 对象就有可能变得相当臃肿. 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module) ...
- 深入理解Vuex 模块化(module)
todo https://www.jb51.net/article/124618.htm
- 【mock】后端不来过夜半,闲敲mock落灯花 (mockjs+Vuex+Vue实战)
mock的由来[假] 赵师秀:南宋时期的一位前端工程师 诗词背景:在一个梅雨纷纷的夜晚,正处于项目编码阶段,书童却带来消息:写后端的李秀才在几个时辰前就赶往临安度假去了,!此时手头仅有一个简单 ...
- Vuex、Flux、Redux、Redux-saga、Dva、MobX
https://www.jqhtml.com/23003.html 这篇文章试着聊明白这一堆看起来挺复杂的东西.在聊之前,大家要始终记得一句话:一切前端概念,都是纸老虎. 不管是Vue,还是 Reac ...
- vuex分模块2
深入理解Vuex 模块化(module) 转载 2017-09-26 作者:ClassName 我要评论 本篇文章主要介绍了Vuex 模块化(module),小编觉得挺不错的,现在分享给大 ...
随机推荐
- 某个应用的CPU使用率居然达到100%,我该怎么做?(三)
某个应用的CPU使用率居然达到100%,我该怎么做?(三) 1. 引 你们好,可爱的小伙伴们^_^! 咱们最常用什么指标来描述系统的CPU性能呢?我想你的答案,可能不是平均负载,也不是CPU上下文切换 ...
- 爬虫示例--requests-module
reuqests_test .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { ...
- C++ I/O库练习
编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中,并输出. 思路:1.以读的模式打开文件“目录.txt”: 2.先创建str ...
- 关于django中的rest_framework的使用
rest_framework框架的认识 它是基于Django的,帮助我们快速开发符合RESTful规范的接口框架. 一 路由 可以通过路由as_view()传参 根据请求方式的不同执行对应不 ...
- @PathVariable、@RequestParam、@RequestBody注解
讲解更加详细的参考资料 https://blog.csdn.net/u011410529/article/details/66974974 https://www.cnblogs.com/soul-w ...
- oracle trim无效?
这里说说如果是全角空格怎么去除 方法一 trim(TO_SINGLE_BYTE('aaa')) 方法二 SELECT TRIM(replace('aaa',' ','')) FROM dual
- git代码提交步骤
常用的步骤: 1)假如本地想关联git仓库,那么先git init,git remote add origin [git地址] 2)假如是想直接从git仓库拉下来,那么git clone [git地 ...
- SQL语句之-函数
六.函数 1.文本处理函数 2.日期和时间处理函数 MySQL数据库:SELECT * FROM orders WHERE YEAR(order_date)=2012 七.汇总数据 1.AVG()函 ...
- [CSP-S模拟测试]:字符(模拟+剪枝)
题目传送门(内部题33) 输入格式 第一行,两个整数$T,C$,表示测试数据组数和字符种类数.对于每组数据:第一行,一个正整数$M$:接下来的$M$行,每行两个整数$P_k,X_k$($S$的下标从$ ...
- JS基础入门篇(二十四)—DOM(上)
1.常用的节点类型,nodeType,attributes,childNodes. 1.元素节点 - 1 2.属性节点 - 2 3.文本节点 - 3 4.注释节点 - 8 5.文档节点 - 9 查看节 ...