SoFunction
Updated on 2025-04-05

Application of mapState idea in vuex

background:

During the requirements development process, some interfaces return many fields that need to be displayed on the page. These fields can usually be encapsulated as computed properties in a .vue file, or the corresponding fields can be reassigned to fields in data for ease of use. as follows:

computed(){
  count1(){
    return .count1
  },
  count2(){
    return .count2
  },
  // ...
  // Imagine.  You have to write similar code 5 times or 10 times}

But no matter which method, it will bring a lot of code redundancy, which is extremely uncomfortable. To solve this phenomenon, this article borrowed and usedvuex middlemap The idea of ​​the method greatly reduces redundant code and can perform unified fault-tolerant processing of data acquisition.

1. Map method

The basic state extraction usage method in vuex can be used in the following ways:

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

at the same timevuex I also noticed the problem. When there is a lot of data to be obtained in the store, this method will generate great code redundancy and repeat codes will go everywhere. You will see a lot of definitions of computed attributes, as well as long-link object attribute extraction. thereforevuex Define a map method for batch acquisitionstore Specified data in .
Thismap A method is actually a factory function (higher-order function) used to produce a specific form of function. The following is the source code, you can seemapState In fact, an object will be returned in the endres, resEach property in it is a method, and this method returnsstate value in .

  var mapState = normalizeNamespace(function (namespace, states) {
    // Define an object to store a method to obtain a specified attribute    var res = {};
    normalizeMap(states).forEach(function (ref) {
      var key = ;
      var val = ;
      // Definition Method to get the specified attribute in the specified object      res[key] = function mappedState () {
        var state = this.$;
        var getters = this.$;
        // Find the specified store module object based on namespace        if (namespace) {
          var module = getModuleByNamespace(this.$store, 'mapState', namespace);
          if (!module) {
            return
          }
          state = ;
          getters = ;
        }
        // Get the properties in the store module obtained by specifying namespace        return typeof val === 'function'
          ? (this, state, getters)
          : state[val]
      };
    });
    // Return function object    return res
  });

2. Application

According to this idea, the acquisition method of fields in a complex object can be optimized. The defined factory function is as follows

export const mapTargetValue = (nameSpace, keyList = [])=>{
  const result = {}
  // Note: Do not use arrow function for the return method, otherwise you will not get this  // Here, two forms of keyList can be compatible, refer to the usage form of attribute renaming in mapState  if((keyList)){
    ( key => result[key] = function(){ 
        // Assume here, you can get the namespace object directly on this        // Of course, the complexity of the acquisition of the specified object depends on your code logic        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
}

The method defined is used andmapState The usage is exactly the same. Compared with the previous value method, the number of repeated codes can be greatly reduced. The specific application is as follows

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

This is the end of this article about the application of mapState ideas in vuex. For more related vuex mapState content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!