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

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

  • 在src下建立文件夹store,用于存放各个模块以及根级别的文件

  • 在index.js文件中导出store
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 userManager from './modules/userManager'
import productManager from './modules/productManager' Vue.use(Vuex); //组装模块并导出 store 的地方
export default new Vuex.Store({
//根节点相关
state,
mutations,
getters,
actions, //模块相关
modules: {
um:userManager,
pm:productManager, }, });
  • 在main.js文件的Vue实例中注册store
import Vue from 'vue'
import App from './App'
import router from './router' import store from './store/index' new Vue({
el: '#app',
router,
store, //注册store
components: {App},
template: '<App/>'
});
  • 模块级别的文件中写于自己相关的代码

1、访问模块局部的状态

对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。

//局部mutations
mutations: { //action中提交该mutation
GETALLPRODUCT(state, data) {
//当页面DOM元素即页面结构加载完成后执行此方法
state.ProductList = data;
},
}, //局部getters,根节点状态会作为第三个参数暴露出来
getters: {
getHotProduct (state,getters,rootState) {
return state.ProductList.filter(product => product.type === 1)
},
getHotProductById: (state) => (id) => {
return state.ProductList.find(product => product.id === id)
}
}
}

同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

 actions: {

    getAllProduct(context) {
//局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState: //发送get请求获取API数据
axios.get(' http://127.0.0.1:8000/api/Productdata/')
.then((response) => {
// handle success
context.commit('GETALLPRODUCT', response.data);
console.log('getters',context.getters.getHotProduct) })
}

2、命名空间

  默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

    如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

export default {

  namespaced: true, //拥有自己的命名空间

  state: {
ProductList: [], },
mutations: {
}, actions: {
}, getters: {
getHotProductById: (state) => (id) => {
return state.ProductList.find(product => product.id === id)
} } }

此时,在组件中调用就需要根据路径进行调用:

2.1 调用模块中的state

    computed: {
UserList() {
return this.$store.state.um.UserList //UserList 是在模块中定义的state状态
},
},

2.2 调用模块中getters

        computed:{
hotProductArray(){ return this.$store.getters['pm/getHotProduct'] //调用无参getters }
} methods:{
getProductById(){
this.$store.getters['pm/getHotProductById'](this.id) //调用有参数的getters } }
},

2.3 提交actions

        mounted() {

          this.$store.dispatch("pm/getAllProduct") //提交局部模块的actions
},

3、在带命名空间的模块注册全局 action

若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中。

    //在有命名空间actions中注册全局action因为有root: true,
getAllUserList: {
root: true,
handler (context, payload) {
//发送get请求获取API数据
axios.get(' http://127.0.0.1:8000/api/userdata/')
.then((response) => {
// handle success
context.commit('um/GETALLUSER', response.data); //全局中使用局部的mutation
console.log(response.data) })
.catch((error) => {
// handle error
console.log(error);
})
.finally(() => {
// always executed
}); } // -> 'someAction'
},

此时虽然这个antion在某个模块文件内,但是确实全局的命名空间,因此像分发action这类的操作可以直接这样:

this.$store.dispatch("getAllUserList");

参考文档:https://vuex.vuejs.org/zh/guide/modules.html

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的使用

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

  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. BUUCTF MISC部分题目wp

    MISC这里是平台上比较简单的misc,都放在一起,难一些的会单独写1,二维码图片里藏了一个压缩包,用binwalk -e分离,提示密码为4个数字,fcrackzip -b -c1 -l 4 -u 得 ...

  2. Python之实现一个优先级队列

    问题 怎样实现一个按优先级排序的队列? 并且在这个队列上面每次 pop 操作总是返回优先级最高的那个元素 解决方案 下面的类利用 heapq 模块实现了一个简单的优先级队列: import heapq ...

  3. ubuntu 设置root密码

  4. LINUX搭建网站环境教程

    安装Mysql yum install mysql-server -y 启动Mysql service mysqld restart 此实验使用 mysql 默认账户名和密码,您也可以设置自己的 My ...

  5. Git中crlf自动转换的坑

    新上手一个项目,克隆了代码下来搭环境,一路坑.其中一个sh脚本执行不了,报IOException,java日志除了"找不到文件或文件夹"之外看不出任何信息,手动运行脚本才发现是脚本 ...

  6. Python新建文件夹

    import os os.mkdir('OS-Demo-2') os.makedirs('OS-Demo-3/sub-Dir-1') os.mkdir()和os.makedirs()都可以新建文件夹, ...

  7. Java 基础 - 单行初始化数组 Initialize array in one line

    Code: public class ClassName { private char[] value = new char[]{'a','b'}; private char[] value2 = { ...

  8. magento 为用户注册增加一个字段

    步骤 I. 加一个occupation/title字段到用户注册页,差不多在register.html的54行,在email下方加一个Occupation显示代码 代码: <li>< ...

  9. Shiro学习(23)多项目集中权限管理

    在做一些企业内部项目时或一些互联网后台时:可能会涉及到集中权限管理,统一进行多项目的权限管理:另外也需要统一的会话管理,即实现单点身份认证和授权控制. 学习本章之前,请务必先学习<第十章 会话管 ...

  10. shiro入门笔记之第一个demo创建

    前言 看到这篇文章之前,可能很多小伙伴都没听过shiro,那么shiro是什么呢?shiro是Apache基金会下一个非常有名的开源项目(项目官网: http://shiro.apache.org/ ...