vue项目开发,基于axios二次封装

916 阅读2分钟

功能确立

  1. 读取接口数组,把接口名化为api,调用方法即发送请求
  2. 请求与数据绑定自动化,即返回的数据自动赋值给页面数据(有待商讨)
  3. 防止接口重复调用,表单重复提交

代码

接口数组

//main.js
import myAxios from './assets/myAxios'

//将myAxios绑定到vue原型上面, 虽然有污染原型的嫌疑,但不失为一个好的方法
Vue.prototype.myAxios = myAxios([
  {
    name: 'api1',                       //调用的接口名称
    url: 'https://0.0.0.0:8080/api1'    //接口地址
  },
  {
    name: 'api2',
    url: 'https://0.0.0.0:8080/api2'
  }
  ...
])

调用

mounted () {
    //绑定当前组件,在myAxios.js里面操作当前组件数据
    this.myAxios.bindThis(this)
    
    this.sendUrl()
},
methods:{
    //所有的接口方法都返回一个promise,方便使用async,await
    async sendUrl(){
      await this.myAxios.api1({
        //数据
        data: {
          late: '22.52291',
          lone: '114.05454',
          cityNumr: 440300
        },
        //自定义headers
        headers: {
          "qqq": 123
        }
      }).then((res)=>{
        this.creeTime = res.creeTime
        //默认绑定数据 this.api1 = res
      })
    
      await this.myAxios.api2({
        //数据
        data: {
          userName: "哈哈",
          userTele: 11111111,
        },
        type: 'post'
      }).then((res)=>{
        //默认绑定数据 this.api2 = res
      })
    }
}

核心代码,myAxios.js

四个主要模块

  1. 初始化模块
  2. 请求生成模块
  3. 请求控制模块
  4. 请求处理模块
//myAxios.js
import axios from 'axios'
export default function(arr){
    function _myaxios(){
        this.vueObj = null
        this.status = true  //防止重复提交
    }
    //绑定处于当前的vue组件
    _myaxios.prototype.bindThis = function(object){
        this.vueObj = object
    }
    //生成请求
    _myaxios.prototype.getAxios = function(config){
        //自定义数据
        var _url = config.url
        var _type = config.type
        var _data = config.data
        var _headers = config.headers

        //公共
        var instance = axios.create({
            headers: {
                'Content-Type': 'application/json',
            }
        });

        //请求,目前只添加get,post
        var fatory = {
            get(){
                return instance.get(_url, {
                    params: _data,
                    headers: _headers
                })
            },
            post(){
                return instance.post(_url,data)
            }
        }
        return fatory[_type]()
    }
    //发送请求
    _myaxios.prototype.sendAxios = function(config){
        var _axios = this.getAxios(config)
        
        if(this.status || !config.isBlock){
            config.isBlock ? this.status = false : ''
            _axios.then((res)=>{
                this.status = true

                //默认数据绑定
                this.handlerAxios(config.dataName, res.data.result) 

                config.resolve.call(this.vueObj, res.data.result);
            }).catch(err =>{
                config.reject.call(this.vueObj, res.data.result);
            })
        }
    }
    //处理请求,公共请求处理
    _myaxios.prototype.handlerAxios = function(dataName, data){
        this.vueObj[dataName] = data
    }
    //初始化部分
    var myaxios = new _myaxios()
    arr.forEach(item => {
        myaxios[item.name] = function(config){
            return new Promise((resolve, reject)=>{
                myaxios.sendAxios({
                    resolve,
                    reject,
                    url: item.url,
                    type: config && config.type || 'get',   //接口类型,默认get
                    headers: config && config.headers || {},
                    data: config && config.data || {},
                    dataName: config && config.dataName || item.name,//传入绑定当前vue组件数据,this[dataName] = res
                    isBlock: config && config.isBlock || false,  //是否阻塞发送请求true为阻塞,false为非阻塞,防止重复发送请求
                })
            })
        }
    })

    return myaxios
}