• VUE AXIOS封装三


    处理反复点击,以及错误拦截

    import axios from 'axios'
    import { API } from '@commons/constants'
    import isEmpty from 'lodash/isEmpty'
    
    const Service = {
      API: API,
    
      REQUEST_CACHE: {}, // API请求池
    
      METHODS: {
        GET: 'get',
        POST: 'post',
        DELETE: 'delete',
        PATCH: 'patch',
        PUT: 'put'
      },
    
      generateDefaultConfig () {
        return {
          isRequest: false
        }
      },
      has: function (key) {
        return !!this.REQUEST_CACHE[key]
      },
    
      gather (config) {
        let key =
          config.url +
          (isEmpty(config.params) ? '' : JSON.stringify(config.params))
        if (!this.has(key)) {
          let ajaxConfig = this.generateDefaultConfig()
          Object.assign(ajaxConfig, config, { key })
          this.REQUEST_CACHE[key] = ajaxConfig
        }
        return key
      },
    
      get (url, params, method) {
        let key = this.gather({ url, params, method: method || this.METHODS.GET })
        return this.request(key)
      },
    
      post (url, params) {
        return this.get(url, params, this.METHODS.POST)
      },
    
      put (url, params) {
        return this.get(url, params, this.METHODS.PUT)
      },
    
      delete (url) {
        return this.get(url, {}, this.METHODS.DELETE)
      },
    
      patch (url, params) {
        return this.get(url, params, this.METHODS.PATCH)
      },
    
      request (key) {
        let config = this.REQUEST_CACHE[key]
        return new Promise((resolve, reject) => {
          if (!config.isRequest) {
            config.isRequest = true
            // 处理两个系统不同的请求
            let param = null;
            if(config.key.indexOf('/rbac') > -1){
              param = config.params;
            }else{
              param = {...config.params};
            }
            axios[config.method.toLowerCase()](this.API + config.url,  param)
              .then(res => {
                this.reset(key)
                resolve(res)
              })
              .catch(err => {
                this.reset(key)
                return reject(err)
              })
          }
        })
      },
    
      reset (key) {
        this.REQUEST_CACHE[key] = null
      }
    }
    
    /**
     * 对外暴露的API
     */
    
    export default {
      get: Service.get.bind(Service),
      post: Service.post.bind(Service),
      delete: Service.delete.bind(Service),
      patch: Service.patch.bind(Service),
      put: Service.put.bind(Service)
    }
  • 相关阅读:
    POJ-图论-最短路模板(邻接矩阵)
    POJ-图论-并查集模板
    POJ-排序-归并排序与逆序对
    【题目自解】北京大学2018计算机学科夏令营上机考试
    【算法总结】图论-拓扑排序
    【算法总结】图论-最短路径
    【算法总结】图论-最小生成树
    【算法总结】图论-并查集
    iOS程序的生命周期
    6款好用的Python IDE
  • 原文地址:https://www.cnblogs.com/tylz/p/11858463.html
Copyright © 2020-2023  润新知