vue3+Ts+Axios封装

复制代码
import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import { IResponseData } from './types'
import { ElMessage, ElLoading, ILoadingInstance } from 'element-plus'

type TAxiosOption = {
    baseURL: string;
    timeout: number;
}
 
const config = {
    baseURL: '/api',
    timeout: 5000
}
 
let loading: ILoadingInstance;
 
class Http {
    // service: AxiosInstance;
    service;
    constructor(config: TAxiosOption) {
        this.service = axios.create(config)

        /* 请求拦截  this.service.interceptors.request.use(config => config, error => Promise.reject(error))*/
        this.service.interceptors.request.use((config: AxiosRequestConfig) => {
                loading = ElLoading.service({
                lock: true,
                text: '加载中~~~~',
                // spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
                })

            if (localStorage.getItem('token')) {
                (config.headers as AxiosRequestHeaders).authorization = localStorage.getItem('token') as string
            }
            return config
        }, error => {
            loading.close()
            console.log("error");
            return Promise.reject(error) // 为了可以在代码中catch到错误信息
        })


        /* 响应拦截   this.service.interceptors.response.use(response => response.data, error => Promise.reject(error))*/
        this.service.interceptors.response.use((response: AxiosResponse<any>) => {
            ElMessage.success('请求成功',)
            loading.close()
            const data = response.data
            return response.data

        }, error => {
            loading.close()
            ElMessage.error('请求失败',)
            return Promise.reject(error)
        })
    }


    get<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> {
        return this.service.get(url, { params, ..._object })
    }
    post<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> {
        return this.service.post(url, params, _object)
    }
    put<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> {
        return this.service.put(url, params, _object)
    }
    delete<T>(url: string, params?: any, _object = {}): Promise<IResponseData<T>> {
        return this.service.delete(url, { params, ..._object })
    }
}
 
export default new Http(config)
复制代码

 

posted @   Comedyy  阅读(1703)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示