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

Detailed code for implementing 3D tag cloud in Vue

Preview: Code: Page Sections: <template> &l...

Example of implementing colored progress bar animation using CSS3

Brief Tutorial This is a CSS3 color progress bar ...

How to use MyCat to implement MySQL master-slave read-write separation in Linux

Table of contents Linux-Use MyCat to implement My...

Solution to the welcome to emergency mode message when booting CentOS7.4

Today I used a virtual machine to do an experimen...

Solution for Baidu site search not supporting https (tested)

Recently, https has been enabled on the mobile ph...

Several methods of deploying multiple front-end projects with nginx

I have summarized 3 methods to deploy multiple fr...

How to encapsulate the table component of Vue Element

When encapsulating Vue components, I will still u...

A brief analysis of the basic concepts of HTML web pages

What is a web page? The page displayed after the ...

How to introduce pictures more elegantly in Vue pages

Table of contents Error demonstration By computed...

Pure CSS to achieve three-dimensional picture placement effect example code

1. Percentage basis for element width/height/padd...

Solve the pitfall of storing boolean type values ​​in localstorage

LocalStorage stores Boolean values Today, when I ...

Summary of Nginx location and proxy_pass path configuration issues

Table of contents 1. Basic configuration of Nginx...

Implementation of nested jump of vue routing view router-view

Table of contents 1. Modify the app.vue page 2. C...

Solution to MySQL master-slave delay problem

Today we will look at why master-slave delay occu...