vue封装axios模块化api接口封装

1.新建接口文件/api/list.js

import request from '../utils/request';
/**
 * 获取风险点详情
 * @param {id}
 * @returns
 */
export function desc(id) {
  return request({
    url: `risk/desc?id=${id}`,
    method: 'get',
  });
}

2.新建接口文件/api/index.js导出list所有接口

import * as list from './list'
export default  {list}

3.封装axios 请求拦截和响应拦截

/**
 * 封装axios请求函数
 */
import axios from 'axios';
import router from '../router';
import { Toast } from 'vant';
const request = axios.create({
  baseURL: process.env.VUE_APP_URL,
  timeout: 10000, // request timeout
});
/**
 * 请求拦截器
 */
request.interceptors.request.use(
  config => {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
      duration: 0,
    });
    const token = localStorage.getItem('Authorization');
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  error => {
    Toast.clear();
    console.log('err' + error); // for debug
    return Promise.reject(error);
  },
);
// 响应器拦截
request.interceptors.response.use(
  response => {
    console.log('请求结束response...'), Toast.clear();
    return Promise.resolve(response.data);
  },
  error => {
    console.log('请求结束error...'), Toast.clear();
    if (error.response.status) {
      const { response } = error;
      errorHandle(response.data.code, response.data.msg);
      return Promise.reject(error.response);
    }
  },
);
export default request;

3.挂载Vue原型

Vue.prototype.$api = api;
Vue.config.productionTip = false;
Vue.prototype.$axios = axios;

4.页面调用

methods: {
    //数据初始化 风险点详情
    desc() {
        return this.$api.list.desc(this.formData.id);
    },
}

你可能感兴趣的:(Vue,vue.js)