// 引入 axios 实例
import axios from "axios";
import { AxiosInstance, CreateAxiosDefaults, AxiosRequestConfig ,AxiosResponse } from "axios";
import { ElLoading } from "element-plus";
// 引入 Loading实例
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.d.js';
import qs from "qs"
import { useUser } from '@/store/user';
const {userInfo} = useUser()
type RequestConfig = {
interceptors?: { request: { use: () => {} } }
showLoading?: boolean,
method?: string
} & AxiosRequestConfig
class Http {
instance: AxiosInstance;
showLoading: boolean;
loading?: LoadingInstance; //element Loading
interceptors?: any
constructor(config: RequestConfig) {
this.instance = axios.create(config);
this.interceptors = config.interceptors;
this.showLoading = config.showLoading ?? false;
//请求拦截
this.instance.interceptors.request.use(
(config) => {
config.params={'_':Date.now(),...config.params};
if (this.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: "加载中...",
});
}
if (
config.method?.toLocaleUpperCase() === 'POST'
) {
config.data = qs.stringify(config.data)
}
config.headers['token']=userInfo.data?.token
return config;
},
(err) => {
return err;
}
);
//响应拦截
this.instance.interceptors.response.use(
(res:AxiosResponse) => {
this.loading?.close();
if (res.data.code != "success") {
return Promise.reject({msg:'接口数据错误',data:res.data})
} else {
return res.data;
}
},
(err) => {
this.loading?.close();
return err;
}
);
}
request<T>(config: RequestConfig): Promise<T> {
this.showLoading = Boolean(config.showLoading ?? this.loading);
return this.instance.request<any, any>(config)
}
get<T>(config: RequestConfig): Promise<T> {
return this.request<T>({ ...config, method: "get" });
}
post<T>(config: RequestConfig): Promise<T> {
return this.request<T>({ ...config, method: "post" });
}
}
export default new Http({
baseURL: "/",
timeout: 10000,
});
vue3+ ts axios封装
于 2023-03-10 16:39:21 首次发布