基于axios简单的二次封装

143 阅读1分钟

基于axios 和引入element-ui

1.在src 目录下创建 utils 目录,新建 request.js 文件

src-->utils-->requst.js

在request.js 中创建axios的实例,配置请求拦截器 和 配置响应拦截器
import { Loading } from 'element-ui'
import axios from 'axios'
// 使用 create 创建 axios 的实例
const request = axios.create({
  baseURL: 'xxx',
  timeOut: 5000
})
// 声明变量,用来存储 Loading 组件的实例对象
let loadingInstance = null

// 配置请求拦截器
request.interceptors.request.use((config) => {
  // 展示 loading 效果
  loadingInstance = Loading.service({ fullscreen: true })
  // 配置 Token 认证
  config.headers.Authorization = 'Bearer xxx'
  console.log(config)
  // 这是固定写法
  return config
})

// 配置响应拦截器
request.interceptors.response.use((response) => {
  // 关闭 loading 效果
  loadingInstance.close()
  return response
})
export default request

2.在src目录下创建 API文件夹,新建 例如请求文章的接口 articleAPI.js

如果还有其他接口,继续在 API 文件下,新建其他的js文件

// 导入 request.js
import request from '@/utils/request'
// 这只是 get 请求
export const getIndexInfo = function (xxx) {
  return request.get('/api/article', {
    params: { xxx }
  })
}
// 

3.使用的展示例子

// 在其他组件导入  getIndexInfo
import { getIndexInfo } from '@/API/indexApi'
export default {
  methods: {
    async get() {
      const { data: res } = await getIndexInfo(xxx)
      console.log(res)
    }
  }
}