Application of mapState idea in vuex

Application of mapState idea in vuex

background:

During the demand development process, some interfaces return results with many fields that need to be displayed on the page. Usually, these fields can be encapsulated as calculated properties in the .vue file, or the corresponding fields can be reassigned to the fields in data to achieve the purpose of ease of use. as follows:

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

But no matter which method is used, it will bring a lot of code redundancy, which is extremely uncomfortable. To solve this problem, this article borrows the idea of ​​​​using the map method in vuex , which greatly reduces the redundant code and can perform unified fault-tolerant processing on data acquisition.

1. Map method

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

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

At the same time, vuex also noticed the problem. When there is a lot of data to be obtained in the store, this method will generate a lot of code redundancy and repeated code everywhere. You will see lots of computed property definitions, as well as long chains of object property extraction. Therefore, vuex defines a map method to obtain specified data in store in batches.
This map method is actually a factory function (higher-order function) that is used to produce functions of a specific form. The following is the source code. You can see that mapState will eventually return an object res . Each attribute in res is a method, and this method returns the value in state .

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

2. Application

Following this idea, the way to obtain fields in a complex object can be optimized. The factory function is defined as follows

export const mapTargetValue = (nameSpace, keyList = [])=>{
  const result = {}
  // Note: Do not use arrow functions for the returned method, otherwise you will not be able to get this
  // Two forms of keyList are compatible here, refer to the usage form of attribute renaming in mapState if(Array.isArray(keyList)){
    keyList.forEach( key => result[key] = function(){ 
        // Here we assume that the namespace object can be obtained directly on this // Of course, the complexity of obtaining 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 usage of this method is exactly the same as mapState . Compared with the previous value-taking method, the amount of repeated code can be greatly reduced. The specific applications are 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 relevant vuex mapState content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use provide to implement state management in Vue3
  • Vue front-end development auxiliary function state management detailed example
  • The practical process of login status management in the vuex project
  • Quickly master how to get started with Vuex state management in Vue3.0
  • How to understand Vue's simple state management store mode
  • How to use vuex in Vue project
  • Use of vuex namespace
  • Vue state management: using Pinia instead of Vuex

<<:  Example of Html shielding right-click menu and left-click typing function

>>:  Solve the problem of specifying udp port number in docker

Recommend

Eclipse configures Tomcat and Tomcat has invalid port solution

Table of contents 1. Eclipse configures Tomcat 2....

Detailed explanation of the practical use of HTML table layout

When is the table used? Nowadays, tables are gene...

Summary of four situations of joint query between two tables in Mysql

Generally speaking, in order to get more complete...

100-1% of the content on the website is navigation

Website, (100-1)% of the content is navigation 1....

Example of Html shielding right-click menu and left-click typing function

Disable right-click menu <body oncontextmenu=s...

Detailed explanation of the MySQL MVCC mechanism principle

Table of contents What is MVCC Mysql lock and tra...

Use elasticsearch to delete index data regularly

1. Sometimes we use ES Due to limited resources o...

Detailed comparison of Ember.js and Vue.js

Table of contents Overview Why choose a framework...

Javascript to achieve the drag effect of the login box

This article shares the specific code of Javascri...

Html sample code for reading and displaying pictures in a local folder

One purpose Select a local folder on the Html pag...

18 Web Usability Principles You Need to Know

You can have the best visual design skills in the...

A brief discussion on using Vue to complete the mobile apk project

Table of contents Basic Configuration Entry file ...