在vue中对axios的封装

安装axios和qs:

npm install axios --save
npm install qs --save
npm install vant --save

单独新建一个http.js:

var config = {
    _url: 'http://www,baidu.com',
}
//非生产环境时使用测试环境配置
if (process.env.NODE_ENV !== 'production') {
  config = {
    _url: '/api'
  }
}

import axios from 'axios';
import qs from "qs";
import ls from './storage.js'
import { Toast,Dialog } from 'vant';
import router from "./router";
//axios 过滤数据 拦截-103代表未登录或者登录过期 -102代表活动未开启或者活动已结束
axios.interceptors.response.use(res => {
    if(res.data.status == -102){
      Dialog.alert({
        message: res.data.message
      }).then(() => {
        window.location.href = 'https://www.baidu.com'
      });
      return;
    }else if (res.data.status == -103) {
      Dialog.alert({
        message: res.data.message
      }).then(() => {
        router.push('/')
      });
      return;
    }
  return res.data;
}, error => {
  return Promise.reject(error);
});

let _ajax = function (opts) {
  let url = base._url +'/test'+ opts.url;
  let data = opts.data || {};
  
  const success = opts.success || function (res) { console.log(res) };
  const error = opts.error || function (err) { console.log(err) };
  const method = opts.method || 'post';
  if (opts.auth) {
      const uid = ls.get('uid') || 0;
      uid && (data.uid = uid);
  }
  
  var responseType = opts.responseType || 'json';
  data = qs.stringify(data);
  let _toast;
  if(!opts.codeImg){
    _toast = Toast({
      type:'loading',
      duration: 0,       // 持续展示 toast
      forbidClick: true, // 禁用背景点击
      loadingType: 'spinner'//circular--小圆圈,spinner--小花朵
    });
  }
  axios({
      params: method == 'get' ? data : '',
      method: method,
      url: url,
      data: data,
      responseType,
      headers: {'x-requested-with': 'XMLHttpRequest'}
  }).then((res) => {
      _toast && Toast.clear();
      if(res){
        success && success(res)
      }
  }).catch((err) => {
    _toast && Toast.clear();
    error && error(err)
  });
}
//用户登录成功后才能使用
let userAjax = function (opts) {
  opts = opts || {};
  opts.auth = true;
  _ajax(opts);
}

export {
  _ajax,
  userAjax
}

对localStorage的封装命名为storage.js:

let ls ={
    set(key,value){
        localStorage.setItem(key,JSON.stringify(value));
    },
    get(key){
        return localStorage.getItem(key)?JSON.parse(localStorage.getItem(key)) : null;
    },
    remove(key){
        localStorage.removeItem(key)
    }
}
export default ls;

在main.js引入,生成为vue的实例:

import {_ajax,userAjax} from './http.js' 
Vue.prototype.ajax = _ajax;
Vue.prototype.userAjax = userAjax;

在vue组件中的script使用:

methods:{
   orderDetail(){
        var _this = this
         this.ajax({
            url: '/orderDetail',
            data:{
                orderId:_this.orderId
            },
            success: function (res) {
                  if (res.status == 1) {
                       _this.detail = res.data;
                   }else{
                      Toast(res.message)
                  }
            }
          });
    },
}

大功告成了!!!!!

你可能感兴趣的:(在vue中对axios的封装)