vue3結(jié)合typescript中使用class封裝axios
vue3 + Ts 中 如何 封裝 axios
安裝 axios 和 Element-plus
yarn add axios // 因?yàn)樵谡埱笾惺褂玫搅?loading yarn add element-plus@2.2.12
在 request 文件中 創(chuàng)建 三個(gè)文件: 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; } // 繼承接口: 定義每個(gè)請求的攔截器并且設(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)的實(shí)例的攔截器 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.所有示實(shí)例的請求攔截 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; } ); // 所有實(shí)例響應(yīng)攔截 this.instance.interceptors.response.use( (res) => { // 通過http的錯(cuò)誤碼 // 服務(wù)器返回的status const data = res.data; // 清除loading this.loading?.close(); if (data.returnCode === '-1001') { console.log('請求失敗,錯(cuò)誤信息'); } else { return data; } }, (err) => { // 4xx -> 5xx 在這里攔截 if (err.response.status == 404) { console.log('404 的錯(cuò)誤'); } return err; } ); } request<T>(config: HRequestConfig<T>): Promise<T> { return new Promise((resolve, reject) => { // 1. 單個(gè)請求的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); } // 不影響下一個(gè)loading 的使用 this.showLoading = DEFAULT_LOADING; // 返回結(jié)果 resolve(res); }) .catch((err) => { // 不影響下一個(gè)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; // 請求等待時(shí)間 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)文章
前端通過vue調(diào)用后端接口導(dǎo)出excel表格基本步驟
在Vue前端項(xiàng)目中,可通過axios庫發(fā)送請求至后端獲取Excel下載鏈接,文中通過代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-10-10Vue使用axios進(jìn)行數(shù)據(jù)異步交互的方法
大家都知道在Vue里面有兩種出名的插件能夠支持發(fā)起異步數(shù)據(jù)傳輸和接口交互,分別是axios和vue-resource,同時(shí)vue更新到2.0之后,宣告不再對vue-resource更新,而是推薦的axios,今天就講一下怎么引入axios,需要的朋友可以參考下2024-01-01快速解決 keep-alive 緩存組件中定時(shí)器干擾問題
文章介紹了在使用keep-alive緩存組件時(shí),如何在組件被緩存后清理定時(shí)器以避免干擾其他組件的邏輯,通過在deactivated鉤子中清理定時(shí)器,可以確保組件被緩存時(shí)不會繼續(xù)運(yùn)行定時(shí)器,感興趣的朋友一起看看吧2025-02-02axios上傳文件錯(cuò)誤:Current?request?is?not?a?multipart?request
最近工作中使用vue上傳文件的時(shí)候遇到了個(gè)問題,下面這篇文章主要給大家介紹了關(guān)于axios上傳文件錯(cuò)誤:Current?request?is?not?a?multipart?request解決的相關(guān)資料,需要的朋友可以參考下2023-01-01Vue?Router動態(tài)路由實(shí)現(xiàn)實(shí)現(xiàn)更靈活的頁面交互
Vue?Router是Vue.js官方的路由管理器,用于構(gòu)建SPA(單頁應(yīng)用程序),本文將深入探討Vue?Router的動態(tài)路由功能,希望可以幫助大家更好地理解和應(yīng)用Vue.js框架2024-02-02