axios+element-ui封装接口

在很多时候 我们直接使用axios调用post get等方法时,会有大量的繁琐引用和冗余,所以将接口封装之后再调用不失为一种更好的办法:
首先 我们先利用axios+element-ui 来封装请求方法及动效

import axios from "axios"
import { Loading, Message, MessageBox } from "element-ui"
import store from "@/store"
//定义等待时长
let loadingCount = 0;
//定义等待实例
let loadingInstance = null
// 请求开始等待
function startLoading() {
    loadingCount++
    loadingInstance = Loading.service({
        lock: false,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0,0,0,0.6)"
    })
}
// 请求等待结束
function stopLoading() {
    loadingInstance.close()
    loadingInstance = null
    loadingCount = 0
}
//检查等待是否可结束
function checkLoading() {
    loadingCount--
    if (loadingCount <= 0 && loadingInstance !== null) {
        stopLoading()
    }
}
//下载文件
function downloadFile(res) {
    const type = res.headers["content-type"]
    const filename = decodeURIComponent(res.headers['content-disposition'].split(';filename')[1])
    const blob = new Blob([res.data], { type })
    const a = document.createElement("a")
    const url = window.URL.createObjectURL(blob)
    a.href = url
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(url)
}
//创建一个axios 实例
const AxiosHttp = axios.create()
// 请求配置
AxiosHttp.interceptors.request.use(
    (config) => {
        if (!config.silence) startLoading()
        const { token, baseUrl } = store.getters
        // 覆盖默认配置
        config = { ...config, baseUrl, timeout: 30000 }
        // 身份令牌
        token && (config.headers['Authorization'] = token)
        return config
    },
    (error) => {
        stopLoading()
        return Promise.reject(error)
    }
)
// 相应配置
AxiosHttp.interceptors.response.use(
    (response) => {
        checkLoading()
        const res = response.data
        if (res instanceof Blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.readAsText(res)
                reader.onload = (e) => {
                    const { result } = e.target
                    if (result.code) {
                        Message.closeAll()
                        Message({ message: result.message, showClose: true, type: "error" })
                        reject(result.message)
                    } else {
                        downloadFile(response)
                        resolve(response)
                    }
                }
            })
        } else if (res.code) {
            if (res.code === xxxx) {
                Message.closeAll()
                MessageBox.confirm("登录已失效,请重新登录", "登录失效", {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'error',
                }).then(() => {
                    store.dispatch("logout").then(() => {
                        location.reload()
                    })
                })
            } else {
                Message.closeAll()
                Message({ message: res.message || 'Error', showClose: true, type: "error" })
            }
            return Promise.reject(new Error(res.message || "Error"))
        } else if (!res.code && !res.data && !res.message && res) {
            return res
        } else {
            return res.data
        }
    },
    (error) => {
        stopLoading()
        Message.closeAll()
        Message({ messag: error.message, showClose: true, type: "error" })
        return Promise.reject(error)
    }
)
export default AxiosHttp

之后将从后端得到的接口地址进行封装:

import http from "@/apis/http.js"
export function fetchUserList(params) {
    return http.get('/userlist', { params })
}
export function fetchUserList1(params) {
    return http.post('/userlist', params)
}
export function fetchUserList2(params) {
    return http.put('/userlist', params)
}
export function fetchUserList3(params) {
    return http.delete('/userlist', { data: params })
}
export function fetchUserList5(params) {
    return http.get('/userlist', { params }, { silence: true }) //不显示加载动画
}
export function fetchUserList4(params) {
    return http.get('/userlist', { params, responseType: 'Blob' }) //下载文件
}

在页面上使用

<template>
  <div class="home">
    <div>
      <img alt="Vue logo" src="../assets/logo.png" />
      <div><el-button @click="handleOpen">打开</el-button></div>
    </div>
  </div>
</template>
<script>
import { fetchUserList } from "@/apis/user";
export default {
  name: "Home",
  methods: {
    async handleOpen() {
      this.dialogFormVisible = true;
      let list = await fetchUserList({ user: 123 });
      console.log(list);
    },
  },
};
</script>