Vuex mapState 思想应用

828 阅读2分钟

背景:

在需求开发过程中,有的接口返回的结果中有很多字段需要展示到页面上。通常可以将这些字段在.vue文件中封装为计算属性,或者重新将对应字段赋值到 data 中的字段来达到便于使用的目的。如下:

computed(){
  count1(){
	return this.targetObj.count1
  },
  count2(){
	return this.targetObj.count2
  },
  // ...
  // 想象一下。你要写 5 遍 或者 10 遍类似的代码
}

但是不管哪种方法,都会带来大量的代码冗余,极为难受。为解决这种现象,本文借用了使用了vuex 中 map 方法的思想,极大的缩减了冗余代码,并且能够对数据获取做统一的容错处理

map方法:

vuex 中基本的 state 提取使用方法,可通过 以下方式:

computed(){
  count(){
	return this.$store.count
  }
}

同时 vuex 也同样注意到了问题,当 store 中要获取的数据很多时,这种方式将会产生极大的代码冗余,重复代码遍地走。你将会看到大量的计算属性的定义,以及长链路的对象属性提取。因此vuex 定义了一种 map 方法,用来批量的获取 store 中的指定数据。 这种 map 方法实际上就是一种 工厂函数(高阶函数),用来生产特定形式的函数。以下是源码,可以看到,mapState 其实最终会返回一个对象 res, res中的每个属性都是一个方法,而这个方法返回 state 中的值。

  var mapState = normalizeNamespace(function (namespace, states) {
	// 定义一个对象 用于存储 获取指定属性的方法
    var res = {};
    normalizeMap(states).forEach(function (ref) {
      var key = ref.key;
      var val = ref.val;
	  // 定义 获取指定对象中指定属性的方法
      res[key] = function mappedState () {
        var state = this.$store.state;
        var getters = this.$store.getters;
		// 根据 namespace 查找指定的 store 模块对象
        if (namespace) {
          var module = getModuleByNamespace(this.$store, 'mapState', namespace);
          if (!module) {
            return
          }
          state = module.context.state;
          getters = module.context.getters;
        }
		// 获取通过指定 namespace 得到的 store module 中的属性
        return typeof val === 'function'
          ? val.call(this, state, getters)
          : state[val]
      };
    });
	// 返回 函数对象
    return res
  });

应用:

仿照这种思想,可以对某个复杂对象中的字段的获取方式进行优化。定义的工厂函数如下所示

export const mapTargetValue = (nameSpace, keyList = [])=>{
  const result = {}
  // 注意:返回的方法不要使用箭头函数,否则拿不到 this
  // 这里 可以兼容两种形式的 keyList ,参考 mapState 中属性重命名的使用形式
  if(Array.isArray(keyList)){
    keyList.forEach( key => result[key] = function(){ 
		// 这里假设 可以直接在 this 上 获取得到 namespace对象
		// 当然 指定对象的获取复杂程度取决于 你的代码逻辑
		return this[nameSpace][key] || 0
	})   
  }else if(typeof keyList === 'object' && keyList){
    for(let key in keyList){
      result[keyList[key]] = function(){ return this[nameSpace][key] || 0}
    }
  }
  return result
}

定义的该方法使用方式与 mapState 使用方式完全一致。与之前的取值方式相比,可大大缩减重复代码量。具体应用如下

computed: {
	...mapTargetValue("targetObj", ["count1", "count2"]),
	...mapTargetValue("targetObj", { count1: "count3", count2: "count4"}),
}