前言
记得之前有一次面试问过我vuex的内容过多该怎么处理?可能我当时理解错了,我以为他考我其他的储存方式,我回答内容过多的话可以借助于浏览器缓存,利用sessionStorage,cookie等方式进行储存。
下来仔细一思考,当然回答肯定是不正确的,想起了vuex中的modules
,突然恍然大悟,原来这道题考的是模块化处理。
目录
一、何为模块化处理?
这里可以借用官方解释:由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
注:我们的路由管理router冗余同样可以采用类似如下的模块化操作。
二、如何引入模块化?
这里跳过vuex的安装教程,如需安装,可参考官网教程:vuex安装教程
1.vuex基本目录
在store下新建module文件夹,module文件夹下里面可以存放不同的模块,同时module文件夹下新建index.js
,用于批量导出模块。
2.A模块
/*A模块*/
export default {
namespaced: true,//命名空间的模块,后面会使用到
state:{
testA:null,
testTwo:null
},
mutations:{
setTestA(state,testA){
state.testA=testA
},
settestTwo(state,testTwo){
state.testTwo=testTwo
}
},
getters:{
},
actions:{
}
}
A模块拥有自己的 state、mutation、action、getter,同样B、C模块基本结构也是如此
3.module/index
import A from './test/a'
import B from './test/b'
import C from './test/c'
export default {
A, //A模块
B, //B模块
C //C模块
}
modelu下面的index主要用于导出不同模块
4.store/index
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './module/index'
Vue.use(Vuex)
/**
* Store分为:
* 1、全局性共享状态。
* 2、局部共享状态。 一般具体的功能状态放在自己module中维护
*/
export default new Vuex.Store({
namespaced: true,//带命名空间的模块
state: { // 全局共享状态
bus: null // 总线
},
mutations: {
setBus(state,bus){
state.bus=bus
}
},
getters: {
},
// 模块局部状态
modules: modules
})
5.main.js注入store
1.vue2.0注入
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
2.vue3.0注入
import store from './store'
createApp(App).use(store).use(router).mount('#app')
三、如何使用模块化
1.直接引用,和日常获取的方式一样
// **1.直接A模块内容获取state**
console.log(this.$store.state.A.testA)
this.$store.commit('A/setTestA','5')
// **2.利用辅助函数获取**
import { mapState } from "vuex";
computed: {
...mapState('A',{
testA:state =>state.testA, //方式一
testTwo:'testTwo' //方式二
})
},
methods:{
...mapMutations('A/test',{
setTestA
}),
},
mounted () { //直接调用取值
let _this=this
console.log(_this.testA,_this.testTwo)
setTimeout(function () {
_this.setTestA(10)
console.log(_this.testA)
},1000)
}
2.利用createNamespacedHelpers获取模块化内容
注:需要搭配
namespace
的使用,通过添加namespaced: true
的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
createNamespacedHelpers只能获取模块化内容仓库,不能获取全局仓库store
// **利用辅助函数获取,每个组件都可以单独引入相关的模块内容,以下是A组件引入A模块内容示例**
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('A')
computed: {
...mapState('A',{
testA:state =>state.testA,//方式一
testTwo:'testTwo' //方式二
})
},
methods:{
...mapMutations({
setTestA:'setTestA'
}),
},
mounted () { //直接调用取值
let _this=this
console.log(_this.testA,_this.testTwo)
setTimeout(function () {
_this.setTestA(20)
console.log(_this.testA)
},1000)
}
createNamespacedHelpers
相比上面的方式更加简洁,可以具体到某个模块,从而达到每个组件都可以单独引入与之相关的模块内容,同时也便于后面的维护。