Vue3+TypeScript封裝axios并進(jìn)行請求調(diào)用的實(shí)現(xiàn)
不是吧,不是吧,原來真的有人都2021年了,連TypeScript都沒聽說過吧?在項(xiàng)目中使用TypeScript雖然短期內(nèi)會增加一些開發(fā)成本,但是對于其需要長期維護(hù)的項(xiàng)目,TypeScript能夠減少其維護(hù)成本,使用TypeScript增加了代碼的可讀性和可維護(hù)性,且擁有較為活躍的社區(qū),當(dāng)居為大前端的趨勢所在,那就開始淦起來吧~
使用TypeScript封裝基礎(chǔ)axios庫
代碼如下:
// http.ts import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import { ElMessage } from "element-plus" const showStatus = (status: number) => { let message = '' switch (status) { case 400: message = '請求錯(cuò)誤(400)' break case 401: message = '未授權(quán),請重新登錄(401)' break case 403: message = '拒絕訪問(403)' break case 404: message = '請求出錯(cuò)(404)' break case 408: message = '請求超時(shí)(408)' break case 500: message = '服務(wù)器錯(cuò)誤(500)' break case 501: message = '服務(wù)未實(shí)現(xiàn)(501)' break case 502: message = '網(wǎng)絡(luò)錯(cuò)誤(502)' break case 503: message = '服務(wù)不可用(503)' break case 504: message = '網(wǎng)絡(luò)超時(shí)(504)' break case 505: message = 'HTTP版本不受支持(505)' break default: message = `連接出錯(cuò)(${status})!` } return `${message},請檢查網(wǎng)絡(luò)或聯(lián)系管理員!` } const service = axios.create({ // 聯(lián)調(diào) // baseURL: process.env.NODE_ENV === 'production' ? `/` : '/api', baseURL: "/api", headers: { get: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, post: { 'Content-Type': 'application/json;charset=utf-8' } }, // 是否跨站點(diǎn)訪問控制請求 withCredentials: true, timeout: 30000, transformRequest: [(data) => { data = JSON.stringify(data) return data }], validateStatus() { // 使用async-await,處理reject情況較為繁瑣,所以全部返回resolve,在業(yè)務(wù)代碼中處理異常 return true }, transformResponse: [(data) => { if (typeof data === 'string' && data.startsWith('{')) { data = JSON.parse(data) } return data }] }) // 請求攔截器 service.interceptors.request.use((config: AxiosRequestConfig) => { //獲取token,并將其添加至請求頭中 let token = localStorage.getItem('token') if(token){ config.headers.Authorization = `${token}`; } return config }, (error) => { // 錯(cuò)誤拋到業(yè)務(wù)代碼 error.data = {} error.data.msg = '服務(wù)器異常,請聯(lián)系管理員!' return Promise.resolve(error) }) // 響應(yīng)攔截器 service.interceptors.response.use((response: AxiosResponse) => { const status = response.status let msg = '' if (status < 200 || status >= 300) { // 處理http錯(cuò)誤,拋到業(yè)務(wù)代碼 msg = showStatus(status) if (typeof response.data === 'string') { response.data = { msg } } else { response.data.msg = msg } } return response }, (error) => { if (axios.isCancel(error)) { console.log('repeated request: ' + error.message) } else { // handle error code // 錯(cuò)誤拋到業(yè)務(wù)代碼 error.data = {} error.data.msg = '請求超時(shí)或服務(wù)器異常,請檢查網(wǎng)絡(luò)或聯(lián)系管理員!' ElMessage.error(error.data.msg) } return Promise.reject(error) }) export default service
取消多次重復(fù)的請求版本
在上述代碼加入如下代碼:
// http.ts import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import qs from "qs" import { ElMessage } from "element-plus" // 聲明一個(gè) Map 用于存儲每個(gè)請求的標(biāo)識 和 取消函數(shù) const pending = new Map() /** * 添加請求 * @param {Object} config */ const addPending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join('&') config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => { if (!pending.has(url)) { // 如果 pending 中不存在當(dāng)前請求,則添加進(jìn)去 pending.set(url, cancel) } }) } /** * 移除請求 * @param {Object} config */ const removePending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join('&') if (pending.has(url)) { // 如果在 pending 中存在當(dāng)前請求標(biāo)識,需要取消當(dāng)前請求,并且移除 const cancel = pending.get(url) cancel(url) pending.delete(url) } } /** * 清空 pending 中的請求(在路由跳轉(zhuǎn)時(shí)調(diào)用) */ export const clearPending = () => { for (const [url, cancel] of pending) { cancel(url) } pending.clear() } // 請求攔截器 service.interceptors.request.use((config: AxiosRequestConfig) => { removePending(config) // 在請求開始前,對之前的請求做檢查取消操作 addPending(config) // 將當(dāng)前請求添加到 pending 中 let token = localStorage.getItem('token') if(token){ config.headers.Authorization = `${token}`; } return config }, (error) => { // 錯(cuò)誤拋到業(yè)務(wù)代碼 error.data = {} error.data.msg = '服務(wù)器異常,請聯(lián)系管理員!' return Promise.resolve(error) }) // 響應(yīng)攔截器 service.interceptors.response.use((response: AxiosResponse) => { removePending(response) // 在請求結(jié)束后,移除本次請求 const status = response.status let msg = '' if (status < 200 || status >= 300) { // 處理http錯(cuò)誤,拋到業(yè)務(wù)代碼 msg = showStatus(status) if (typeof response.data === 'string') { response.data = { msg } } else { response.data.msg = msg } } return response }, (error) => { if (axios.isCancel(error)) { console.log('repeated request: ' + error.message) } else { // handle error code // 錯(cuò)誤拋到業(yè)務(wù)代碼 error.data = {} error.data.msg = '請求超時(shí)或服務(wù)器異常,請檢查網(wǎng)絡(luò)或聯(lián)系管理員!' ElMessage.error(error.data.msg) } return Promise.reject(error) }) export default service
在路由跳轉(zhuǎn)時(shí)撤銷所有請求
在路由文件index.ts中加入
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' import Login from '@/views/Login/Login.vue' //引入在axios暴露出的clearPending函數(shù) import { clearPending } from "@/api/axios" .... .... .... const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach((to, from, next) => { //在跳轉(zhuǎn)路由之前,先清除所有的請求 clearPending() // ... next() }) export default router
使用封裝的axios請求庫
封裝響應(yīng)格式
// 接口響應(yīng)通過格式 export interface HttpResponse { status: number statusText: string data: { code: number desc: string [key: string]: any } }
封裝接口方法
舉個(gè)栗子,進(jìn)行封裝User接口,代碼如下~
import Axios from './axios' import { HttpResponse } from '@/@types' /** * @interface loginParams -登錄參數(shù) * @property {string} username -用戶名 * @property {string} password -用戶密碼 */ interface LoginParams { username: string password: string } //封裝User類型的接口方法 export class UserService { /** * @description 查詢User的信息 * @param {number} teamId - 所要查詢的團(tuán)隊(duì)ID * @return {HttpResponse} result */ static async login(params: LoginParams): Promise<HttpResponse> { return Axios('/api/user', { method: 'get', responseType: 'json', params: { ...params }, }) } static async resgister(params: LoginParams): Promise<HttpResponse> { return Axios('/api/user/resgister', { method: 'get', responseType: 'json', params: { ...params }, }) } }
項(xiàng)目中進(jìn)行使用
代碼如下:
<template> <input type="text" v-model="Account" placeholder="請輸入賬號" name="username" > <input type="text" v-model="Password" placeholder="請輸入密碼" name="username" > <button @click.prevent="handleRegister()">登錄</button> </template> <script lang="ts"> import { defineComponent, reactive, toRefs } from 'vue' //引入接口 import { UserService } from '@/api/user' export default defineComponent({ setup() { const state = reactive({ Account: 'admin', //賬戶 Password: 'hhhh', //密碼 }) const handleLogin = async () => { const loginParams = { username: state.Account, password: state.Password, } const res = await UserService.login(loginParams) console.log(res) } const handleRegister = async () => { const loginParams = { username: state.Account, password: state.Password, } const res = await UserService.resgister(loginParams) console.log(res) } return { ...toRefs(state), handleLogin, handleRegister } }, }) </script>
到此這篇關(guān)于Vue3+TypeScript封裝axios并進(jìn)行請求調(diào)用的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue3+TypeScript封裝axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue利用better-scroll實(shí)現(xiàn)輪播圖與頁面滾動詳解
在我們?nèi)粘5捻?xiàng)目開發(fā)中,處理滾動和輪播圖是再常見不過的需求了,下面這篇文章主要給大家介紹了關(guān)于vue利用better-scroll實(shí)現(xiàn)輪播圖與頁面滾動的相關(guān)資料,文中給出了詳細(xì)的示例代碼供大家參考學(xué)習(xí),需要的朋友們下面來一起看看吧。2017-10-10解決vue無法加載文件C:\Users\Administrator\AppData\Roaming\npm\vue.ps
這篇文章主要介紹了解決vue無法加載文件C:\Users\Administrator\AppData\Roaming\npm\vue.ps1因?yàn)樵诖讼到y(tǒng)上禁止運(yùn)行腳本問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03VUE中computed 、created 、mounted的先后順序說明
這篇文章主要介紹了VUE中computed 、created 、mounted的先后順序說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03vue使用關(guān)于speak-tss插件的詳細(xì)介紹及一些配置項(xiàng)
本文詳細(xì)介紹了speak-tss插件在Vue3中的使用方法和配置,首先需要下載依賴,然后引入插件,并進(jìn)行實(shí)例化和配置,配置項(xiàng)包括音量、語言、語音、語速、音調(diào)等,speak-tss支持多種語言和語音,適用于需要文本語音播報(bào)的場景2024-09-09利用Vue3實(shí)現(xiàn)可復(fù)制表格的方法詳解
表格是前端非常常用的一個(gè)控件,本文主要為大家介紹了Vue3如何實(shí)現(xiàn)一個(gè)簡易的可以復(fù)制的表格,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-12-12validate?注冊頁的表單數(shù)據(jù)校驗(yàn)實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了validate?注冊頁的表單數(shù)據(jù)校驗(yàn)實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒值報(bào)錯(cuò)問題
今天小編大家分享一篇解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒值報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Vue使用json-server進(jìn)行后端數(shù)據(jù)模擬功能
這篇文章主要介紹了Vue使用json-server進(jìn)行后端數(shù)據(jù)模擬功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-04-04