Use of API store view in vuex for Vue element front-end application development

Time:2021-11-30
catalogue
  • summary
  • 1. Separation of front and back end and web API priority route design
  • 2. Axios network request processing
    • Post request
    • Get request
  • 3. Use of API, store and view in vuex

    summary

    When we develop Vue applications, we often need to record the contents of some variables, which can be used to carry the interface state, or as the processing of data exchange between pages. Processing these contents can be classified as vuex state control. For example, we often need to access the front-end and back-end data. Generally, we obtain data through encapsulated web API calls, and use the store mode to process relevant data or state changes, and the view is mainly the display processing of the interface. This essay mainly introduces how to integrate the relationship between the three and realize the logical operations such as data acquisition, processing and display.

    Vuex is a state management pattern developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. For details on the differences and relationships among vuex’s related states, getters, movements, actions and modules, please refer to the following: https://vuex.vuejs.org/zh/

    1. Separation of front and back end and web API priority route design

    Web API is an application interface framework, which can build HTTP services to support a wider range of clients (including mobile devices such as browsers, mobile phones and tablets). Asp.net web API is an ideal platform for building restful applications on. Net framework /. Net core. In the current developed application scenarios, we often need to access WinForm client, APP program, website program, and currently popular wechat application. These data should be provided by the same service, which is the web API platform we need to build. As the web API layer is a public interface layer, we can ensure the data consistency of each interface application layer.

    Due to the tendency to completely separate the front and back ends, our back end can be completely supported by the unified construction of Web APIs. We can use the unified interface platform built by. Net framework or. Net core, the web API interface platform simply made by asp.net, or the web API platform built based on the ABP aspnetbilerplate framework.

    In this way, we can build many front-end applications based on these API interfaces, such as web front-end, WinForm front-end, and docking various apps.

    The development method of Vue + element with front and back ends separated is introduced, so the boundary between the front and back ends is very clear. The front end can build the application of the front end by obtaining the corresponding JSON through the network.

    In the front-end processing, it mainly uses the store object in vuex mode to process the request for action and mutation. After obtaining the data, it updates the data in the state. If it is only the data processing of the current page, you can directly obtain the returned data and directly update it to the interface view without storing state information.

    In the early stage of development, we can even use mock data instead of requesting data from the web API without any relationship with the back end. As long as the data structure of mock is consistent with the JSON returned by the web API interface, we can realize rapid docking in the later stage without affecting the existing code processing method.

    2. Axios network request processing

    Before we go further, we need to know some object concepts in vuex and the relationship between them.

    Vuex is a state management pattern developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. For details on the differences and relationships among vuex’s related states, getters, movements, actions and modules, please refer to the following: https://vuex.vuejs.org/zh/

    Before initiating a network request, we need to understand Axios. Axios is an HTTP client based on promise for browsers and nodejs. In essence, it is also an encapsulation of native XHR, but it is an implementation version of promise and conforms to the latest es specification. Here, we only need to know that it is a very powerful network request processing library and has been widely used. We can list several code cases to understand.

    Post request

    
    axios({
        method: 'post',
        url: '/user/12345',
        data: {
            firstName: 'Fred',
            lastName: 'Flintstone'
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

    Get request

    axios
      .get('http://rap2api.taobao.org/app/mock/23080/resources/search',{
          params: {
             id: 5
          }
       })
      .then(res => {
        Console.log ('data is: ', RES);
      })
      .catch((e) => {
        Console.log ('failed to get data ');
      });

    If we want to request data across domains, set the proxy and vue-cli3 project in the configuration file, and write the configuration in vue.config.js.

    Request interception and response interception can be set respectively, and judgment processing can be carried out before the request and response arrive at then. The general processing method is to encapsulate a class such as request class, and then carry out unified processing of the interceptor, such as adding some user identity information before the request.

    // create an axios instance
    const service = axios.create({
      timeout: 5000 // request timeout
    })
    
    //Request interception
    service.interceptors.request.use(
      config => {
    
        if (store.getters.token) {
          config.headers['X-Token'] = getToken()
        }
        return config
      },
      error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
      }
    )

    3. Use of API, store and view in vuex

    Let’s return to the introduction to the use of API, store and view in vuex.

    Let’s take a look at the encapsulation of API request calling classes. As shown below, we have created some API class files for operating data. Each API name corresponds to the centralized processing of a business, including list requests, single requests, addition, deletion, modification, etc. of a specific business, which can be encapsulated in an API class.

    Let’s take a look at the class file definition of product. JS, as shown below.

    Here I use the operation comparison between request and Axios, which are very close, because request is a simple encapsulation of Axios, which mainly intercepts and injects some login information and some response error handling.

    
    import request from '@/utils/request'
    import axios from 'axios'

    In the URL here, the corresponding iqidi will be replaced by the corresponding external domain name through the processing of proxy configuration, so as to obtain the cross domain processing request data. We only need to know that the URL will eventually be converted into a similar domain

    http://www.iqidi.com/h5/GetProductList In this way, the actual address can be requested, and the return is a JSON data set.

    Because of the JS processing part in the Vue view, you can directly import the API to request data, as shown below.

    
    import { GetProductList } from '@/api/product'

    Then we can define a method to obtain API data in the method method method.

    
    methods: {
    getlist(type) {
       GetProductList({ type: type }).then(response => {
         const { data } = response
         this.productlist = data.list
         this.listLoading = false
       })
    }

    This call is the most direct API call and does not introduce the action or mutation encapsulated in the store module for asynchronous or synchronous processing. In general, it is relatively simple to use this method directly, because most page processing or component processing do not need to store the data in the global state, that is, there is no need to process the global store object.

    If we need to store the corresponding information globally, we need to introduce the encapsulation of API calls in the store module, including the processing of action or mutation.

    Let’s first define the store storage class, as shown in the following interface.

    If we need to store data such as product lists in global state, we can consider creating a module under the corresponding store directory, such as product.js, to manage information such as action, mutation and state.

    import { GetProductList, GetProductDetail } from '@/api/product'
    
    const state = {
      productlist: [],
      productdetail: null
    }
    const mutations = {
      SET_PRODUCT_LIST: (state, list) => {
        state.productlist = list
      },
      SET_PRODUCT_DETAIL: (state, detail) => {
        state.productdetail = detail
      }
    }
    
    const actions = {
      //Product list
      getProductList({ commit }, { type }) {
        console.log(type);
        return new Promise((resolve, reject) => {
          GetProductList({ type: type }).then(response => {
            const { data } = response
            commit('SET_PRODUCT_LIST', data)
            resolve(data)
          }).catch(error => {
            reject(error)
          })
        })
      },
    
      //Get product details
      getProductDetail({ commit }, { id }) {
        return new Promise((resolve, reject) => {
          GetProductDetail({ id: id }).then(response => {
            const { data } = response
            commit('SET_PRODUCT_DETAIL', data)
            resolve(data)
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions
    }

    Let’s take a look at it. If we introduce the business class of Store module, then calling code in the interface view is changed to calling the corresponding Action or Mutation.

    
     methods: {
        getlist(type) {
          // GetProductList({ type: type }).then(response => {
          //   const { data } = response
          //   this.productlist = data.list
          //   this.listLoading = false
          // })
    
          this.$store.dispatch('product/getProductList', { type: type }).then(data => {
            this.productlist = data.list
            // this.loading = false
          }).catch((e) => {
            // this.loading = false
          })
        }

    Let’s emphasize here that in general, you can use API class calls in the view module. For each business module that does not need to be cumbersome, you need to create a store module class for corresponding management. Only when these status data need to be shared in multiple pages or components, you can consider introducing the store module class for detailed management.

    We just said that if you need to create a store state management module corresponding to the business module, you need to create a corresponding module class, such as the product.js class file mentioned earlier.

    Among them, the vuex store management class in the modules directory is divided according to the business boundary. Each corresponding business creates a separate file for management (if necessary).

    In index.js, we load these classes according to different namespaces through module dynamic loading for unified use.

    
    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from './getters'
    
    Vue.use(Vuex)
    
    // https://webpack.js.org/guides/dependency-management/#requirecontext
    const modulesFiles = require.context('./modules', true, /\.js$/)
    
    // you do not need `import app from './modules/app'`
    // it will auto require all vuex module from modules file
    const modules = modulesFiles.keys().reduce((modules, modulePath) => {
      // set './app.js' => 'app'
      const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
      const value = modulesFiles(modulePath)
      modules[moduleName] = value.default
      return modules
    }, {})
    
    const store = new Vuex.Store({
      modules,
      getters
    })
    
    export default store

    The above is the details of the use of API store view in vuex for Vue element front-end application development. For more information about Vue, please pay attention to other related articles of developeppaer!

    Recommended Today

    Golden nine silver ten: byte three-sided warp at the front end of a year

    background Recently, I also wrote an article in naked CIGolden nine silver ten: Interview sharing at the front of the year, after many days,Finally summoned up the courage to resume the interview, the reason why the byte face is written separately,Because you really need to know some big factory interview experience in advance, the problem […]