vue3結(jié)合typescript中使用class封裝axios
更新時間:2023年06月13日 10:47:09 作者:阿淮iya
這篇文章主要為大家介紹了vue3結(jié)合typescript中使用class封裝axios實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
vue3 + Ts 中 如何 封裝 axios
安裝 axios 和 Element-plus
yarn add axios // 因為在請求中使用到了 loading yarn add element-plus@2.2.12
在 request 文件中 創(chuàng)建 三個文件: type.ts 、 index.ts 、 config.ts
1.定義接口類型:創(chuàng)建 type.ts 文件
// 引入 axios
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
// 定義接口
export interface HRequestInterceptors<T = AxiosResponse> {
// 請求攔截器(成功與失?。?
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig;
requestInterceptorsCatch?: (error: any) => any;
// 相應(yīng)攔截器(成功與失?。?
responseInterceptor?: (res: T) => T;
responseInterceptorCatch?: (error: any) => any;
}
// 繼承接口: 定義每個請求的攔截器并且設(shè)置請求狀態(tài)顯示
export interface HRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: HRequestInterceptors<T>;
// 是否展示請求加載狀態(tài)
showLoading?: boolean;
}2.根據(jù)1 type 使用 class 封裝axios
// 引入axios
import axios from 'axios';
import type { AxiosInstance } from 'axios';
// 引入類型
import type { HRequestInterceptors, HRequestConfig } from './type';
// 引入加載等待組件
import { ElLoading } from 'element-plus';
// 引入loading 類型:不同版本路勁不同
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
// 請求加載顯示狀態(tài)
const DEFAULT_LOADING = false;
class HRequest {
// 類型
instance: AxiosInstance;
interceptors?: HRequestInterceptors;
showLoading: boolean;
loading?: LoadingInstance;
constructor(config: HRequestConfig) {
// 創(chuàng)建請求
this.instance = axios.create(config);
// 保存基本信息
this.interceptors = config.interceptors;
this.showLoading = config.showLoading ?? DEFAULT_LOADING;
// 使用攔截器
// 1.從config中獲取的攔截器是對應(yīng)的實例的攔截器
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptors,
this.interceptors?.requestInterceptorsCatch
);
// 響應(yīng)攔截類型
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCatch
);
// 2.所有示實例的請求攔截
this.instance.interceptors.request.use(
(config) => {
if (this.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: '請求加載中...',
background: 'rgba(255,255,255,0.5)'
});
}
return config;
},
(err) => {
return err;
}
);
// 所有實例響應(yīng)攔截
this.instance.interceptors.response.use(
(res) => {
// 通過http的錯誤碼
// 服務(wù)器返回的status
const data = res.data;
// 清除loading
this.loading?.close();
if (data.returnCode === '-1001') {
console.log('請求失敗,錯誤信息');
} else {
return data;
}
},
(err) => {
// 4xx -> 5xx 在這里攔截
if (err.response.status == 404) {
console.log('404 的錯誤');
}
return err;
}
);
}
request<T>(config: HRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
// 1. 單個請求的cofig 的處理
if (config.interceptors?.requestInterceptors) {
config = config.interceptors.requestInterceptors(config);
}
// 判斷是否顯示loading
if (config.showLoading) {
this.showLoading = config.showLoading;
}
this.instance
.request<any, T>(config)
.then((res) => {
if (config.interceptors?.responseInterceptor) {
res = config.interceptors.responseInterceptor(res);
}
// 不影響下一個loading 的使用
this.showLoading = DEFAULT_LOADING;
// 返回結(jié)果
resolve(res);
})
.catch((err) => {
// 不影響下一個loading 的使用
this.showLoading = DEFAULT_LOADING;
reject(err);
});
});
}
// 對request 二次封裝
get<T>(config: HRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'GET' });
}
post<T>(config: HRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'POST' });
}
put<T>(config: HRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'PUT' });
}
delete<T>(config: HRequestConfig<T>): Promise<T> {
return this.request<T>({ ...config, method: 'DELETE' });
}
}
export default HRequest;3.創(chuàng)建 config.ts 文件
// 根據(jù)相關(guān)開發(fā)環(huán)境進(jìn)行獲取 BASEURL
export const BASE_URL = process.env.VUE_APP_BASE_API;
// 請求等待時間
export const TIME_OUT = 1000;
// export { BASE_URL, TIME_OUT };
4.新建 serivce統(tǒng)一出口
import HRequest from './request';
//
import { BASE_URL, TIME_OUT } from './request/config';
import localCache from '@/utils/cache';
// 攜帶參數(shù)
const hRequest = new HRequest({
baseURL: BASE_URL,
timeout: TIME_OUT,
interceptors: {
requestInterceptors: (config) => {
// 獲取token 根據(jù) 自己 對token存儲 獲取
const token = localCache.getCache({ key: 'token' });
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
requestInterceptorsCatch(error) {
return error;
},
responseInterceptor: (res) => {
return res;
},
responseInterceptorCatch(error) {
return error;
}
}
});
export default hRequest;5.最后定義請求接口 和 使用
import hRequest from '../index';
// 參數(shù)類型
interface IData {}
// 返回結(jié)果類型
interface IResult{}
// url
enum LoginAPI {
AccontLogin = '/login'
}
// 導(dǎo)出接口 showLoading:loading顯示 :默認(rèn)情況下為不展示
export function accountLoginRequst(data:IData) {
return hRequest.post<IResult>({
url: LoginAPI.AccontLogin,
data,
showLoading: true
});
}
// 使用
accountLoginRequst({userName:'admin',password:'123456'}).then(res=>{
console.log(res)
})以上就是vue3結(jié)合typescript中使用class封裝axios的詳細(xì)內(nèi)容,更多關(guān)于vue3 Ts封裝axios的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue2.0和mintui-infiniteScroll結(jié)合如何實現(xiàn)無線滾動加載
這篇文章主要介紹了vue2.0和mintui-infiniteScroll結(jié)合如何實現(xiàn)無線滾動加載,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
vue中在vuex的actions中請求數(shù)據(jù)實例
今天小編就為大家分享一篇vue中在vuex的actions中請求數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
說說Vue.js中的functional函數(shù)化組件的使用
這篇文章主要介紹了說說Vue.js中的functional函數(shù)化組件的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

