封装一个axios分别可以传form格式和json格式

595 阅读1分钟
/* ajax封装===post
    url:接口名称;
    dataParams:要传给接口的参数;
    callBack:接口调用成功的回调函数;
    type:传参时为form:2还是json:1;
    errorCallBack:接口调用失败时的回调
  */
  commonAjaxPost(url, dataParams, callBack, type, errorCallBack) {
    if (type == 2) {
      new Vue().$axios({
        url: url,
        method: 'post',
        data: dataParams,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          ret = ret.substr(0, ret.length - 1)
          return ret
        }]
      }).then(res => {
        if (typeof callBack == 'function') {
          callBack(res)
        }
      }).catch(error => {
        console.log(error)
        if (typeof errorCallBack == 'function') {
          errorCallBack()
        }
      })
    } else {
      new Vue().$axios({
        url: url,
        method: 'post',
        data: dataParams
      }).then(res => {
        if (typeof callBack == 'function') {
          callBack(res)
        }
      }).catch(error => {
        console.log(error)
        if (typeof errorCallBack == 'function') {
          errorCallBack()
        }
      })
    }
  },
  /* ajax封装===get
    url:接口名称;
    dataParams:要传给接口的参数;
    callBack:接口调用成功的回调函数;
    errorCallBack:接口调用失败时的回调
  */
  commonAjaxGet(url, dataParams, callBack, errorCallBack) {
    new Vue().$axios({
      url: url,
      method: 'get',
      params: dataParams
    }).then(data => {
      if (typeof callBack == 'function') {
        callBack(data)
      }
    }).catch(error => {
      console.log(error)
      if (typeof errorCallBack == 'function') {
        errorCallBack()
      }
    })
  }