Vuex中的模块复用

1,514 阅读2分钟

Vuex中的模块复用

问题背景

在项目实际开发过程中,我们会用到Vuex来管理非常多的数据,项目中公共的数据皆存放在store中,使得前端各个组件之前的交互变得非常轻松。但项目数据稍微增多,模块的数量就会飞速上涨,各个模块穿插了大量的相似功能,往往一次修改就牵一发而动全身,这让开发和维护变得艰难。

一般store的模块结构如图 vuex模块.png

解决思路

公共模块(模块本身不会加载到vuex中)

我把各个模块当中出现的重复功能提取出来,单独放到一个模块中,供其他模块去使用。因为这个模块本身不会被加载到vuex中,所以我们可以直接把它理解为一个简单的库。

// common.js
// 各个模块相同的功能,集合到此公共模块中管理
export default {
  namespaced: true,
  state:{ /*...*/ },
  getters: { /*...*/ },
  mutations:{ /*...*/ },
  actions:{
    test(){
      console.log("test common")
    }
  }
}
A模块

引入了公共模块后别忘了进行一次深拷贝,这里我直接使用了lodash

如果对公共模块的某个部分完全用不上,可以像A模块中这样,直接覆盖了公共模块的actions

//A.js
import common from "./common.js"
import cloneDeep from "lodash/cloneDeep"
let itemA = cloneDeep(common)
//定义A模块的actions
let actions = {
  test(){
    console.log("test common AAA")
  },
  testA(){
    console.log("test AAA")
  }
}
//覆盖公共模块的 actions
itemA.actions = actions
export default itemA
B模块

如果需要在公共模块的基础上添加一些功能,可以像B模块中这样,将新老actions合并

//B.js
import common from "./common.js"
import cloneDeep from "lodash/cloneDeep"
let itemB = cloneDeep(common)
let actions = {
  testB(){
    console.log("test BBB")
  }
}
//合并 actions
itemB.actions = {...itemB.actions, ...actions}
export default itemB

文中案例以actions对象为例,其他对象如:state, getters, mutations等操作与actions相同

vuex入口文件

入口文件的代码与一般项目没有区别,仅需要引入项目中的各个模块即可。

//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import itemA from "./itemA.js"
import itemB from "./itemB.js"
Vue.use(Vuex)
export default new Vuex.Store({
  modules : {
    itemA,
    itemB
  },
  state: { },
  getters: { },
  mutations: { },
  actions: { }
})

加入公共模块后结构如图

vuex模块复用.png

最后

像这样管理起来之后,store的各个模块变得调理清晰了。如果有公共模块中的功能要发生调整,只需要对公共模块中的代码进行改动即可。每个模块中仅存放自身独有的功能。