vue中axios的封装以及简单使用

一、axios的封装

在vue中为了使用axios使用方便,不需要每一个模块进行导入,就需要对其进行封装:

1、新建http.js模块

import axios from 'axios'


// 设置基础apiUrl
axios.defaults.baseURL = 'http://127.0.0.1:8000/';


export default {
  install: function (Vue) {
    Object.defineProperty(Vue.prototype, '$http', {value: axios})
  }
}

2、在main.js中导入

此时vue实例中已经有$http方法了

import MyServerHttp from './plugins/http.js'

Vue.use(MyServerHttp);

3、在需要的地方进行调用

async editUser(context, object) {
//进行调用,其中object._this为vue实例
      const res = await object._this.$http.put(`crm/user/${object.userId}`, object.form);
      const {data, meta: {message, code}} = res.data;
      if (code === 2000) {
        context.dispatch("getAllUserList", {_this:object._this});
        object._this.editDialogFormVisible = false;
        object._this.$message.success(message);
      }
    },

二、拦截器的使用

拦截器是在发送请求之前做一些动作,比如将将token从localstorage中获取添加到请求头中。

// 拦截request,/ 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (config.url !== "login") {
    config.headers['Authorization'] = localStorage.getItem("token");
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

三、响应器的使用

响应器是对响应的内容提前做一些过滤之类的动作,然后返回。

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么

  const res = response.data;

  if (res.count) return response

  if (res.meta.code) {
    if (res.meta.code === 2002) {
      //如果返回的code === 2002,就返回无权限查看内容,不需要将整个response返回
      Message.warning("无权查看对应数据")
    }
    return response

  } else {
    return response;
  }

}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

完整封装代码:

import axios from 'axios'
import {Message} from 'element-ui';

// const MyHttpServer = {};

// MyHttpServer.install = (Vue) => {
//
//   // axios.baseURL = 'http://127.0.0.1:8000/';
//
//   //添加实例方法
//   Vue.prototype.$http = axios
//
// };
//
// export default MyHttpServer


// 设置基础apiUrl
axios.defaults.baseURL = 'http://127.0.0.1:8000/';

axios.defaults.withCredentials = true; // 允许携带cookie


// 拦截request,/ 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (config.url !== "login") {
    config.headers['Authorization'] = localStorage.getItem("token");
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
//
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么

  const res = response.data;

  if (res.count) return response

  if (res.meta.code) {
    if (res.meta.code === 2002) {
      //如果返回的code === 2002,就返回无权限查看内容,不需要将整个response返回
      Message.warning("无权查看对应数据")
    }
    return response

  } else {
    return response;
  }

}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});


export default {
  install: function (Vue) {
    Object.defineProperty(Vue.prototype, '$http', {value: axios})
  }
}
http.js

猜你喜欢

转载自www.cnblogs.com/shenjianping/p/11448247.html