一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務器之家 - 編程語言 - JavaScript - vue.js - Vue3+TypeScript封裝axios并進行請求調用的實現

Vue3+TypeScript封裝axios并進行請求調用的實現

2022-03-02 16:25我的名字豌豆 vue.js

這篇文章主要介紹了Vue3+TypeScript封裝axios并進行請求調用的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

不是吧,不是吧,原來真的有人都2021年了,連TypeScript都沒聽說過吧?在項目中使用TypeScript雖然短期內會增加一些開發成本,但是對于其需要長期維護的項目,TypeScript能夠減少其維護成本,使用TypeScript增加了代碼的可讀性和可維護性,且擁有較為活躍的社區,當居為大前端的趨勢所在,那就開始淦起來吧~

使用TypeScript封裝基礎axios庫

代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from "element-plus"
 
const showStatus = (status: number) => {
  let message = ''
  switch (status) {
    case 400:
      message = '請求錯誤(400)'
      break
    case 401:
      message = '未授權,請重新登錄(401)'
      break
    case 403:
      message = '拒絕訪問(403)'
      break
    case 404:
      message = '請求出錯(404)'
      break
    case 408:
      message = '請求超時(408)'
      break
    case 500:
      message = '服務器錯誤(500)'
      break
    case 501:
      message = '服務未實現(501)'
      break
    case 502:
      message = '網絡錯誤(502)'
      break
    case 503:
      message = '服務不可用(503)'
      break
    case 504:
      message = '網絡超時(504)'
      break
    case 505:
      message = 'HTTP版本不受支持(505)'
      break
    default:
      message = `連接出錯(${status})!`
  }
  return `${message},請檢查網絡或聯系管理員!`
}
 
const service = axios.create({
  // 聯調
  // 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'
    }
  },
  // 是否跨站點訪問控制請求
  withCredentials: true,
  timeout: 30000,
  transformRequest: [(data) => {
    data = JSON.stringify(data)
    return data
  }],
  validateStatus() {
    // 使用async-await,處理reject情況較為繁瑣,所以全部返回resolve,在業務代碼中處理異常
    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) => {
  // 錯誤拋到業務代碼
  error.data = {}
  error.data.msg = '服務器異常,請聯系管理員!'
  return Promise.resolve(error)
})
 
// 響應攔截器
service.interceptors.response.use((response: AxiosResponse) => {
  const status = response.status
  let msg = ''
  if (status < 200 || status >= 300) {
    // 處理http錯誤,拋到業務代碼
    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
    // 錯誤拋到業務代碼
    error.data = {}
    error.data.msg = '請求超時或服務器異常,請檢查網絡或聯系管理員!'
    ElMessage.error(error.data.msg)
  }
  return Promise.reject(error)
})
 
export default service

取消多次重復的請求版本

在上述代碼加入如下代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from "qs"
import { ElMessage } from "element-plus"
 
// 聲明一個 Map 用于存儲每個請求的標識 和 取消函數
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 中不存在當前請求,則添加進去
      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 中存在當前請求標識,需要取消當前請求,并且移除
    const cancel = pending.get(url)
    cancel(url)
    pending.delete(url)
  }
}
 
/**
 * 清空 pending 中的請求(在路由跳轉時調用)
 */
export const clearPending = () => {
  for (const [url, cancel] of pending) {
    cancel(url)
  }
  pending.clear()
}
 
// 請求攔截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
  removePending(config) // 在請求開始前,對之前的請求做檢查取消操作
  addPending(config) // 將當前請求添加到 pending 中
  let token = localStorage.getItem('token')
  if(token){
    config.headers.Authorization = `${token}`;
  }
  return config
}, (error) => {
  // 錯誤拋到業務代碼
  error.data = {}
  error.data.msg = '服務器異常,請聯系管理員!'
  return Promise.resolve(error)
})
 
// 響應攔截器
service.interceptors.response.use((response: AxiosResponse) => {
 
  removePending(response) // 在請求結束后,移除本次請求
  const status = response.status
  let msg = ''
  if (status < 200 || status >= 300) {
    // 處理http錯誤,拋到業務代碼
    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
    // 錯誤拋到業務代碼
    error.data = {}
    error.data.msg = '請求超時或服務器異常,請檢查網絡或聯系管理員!'
    ElMessage.error(error.data.msg)
  }
  return Promise.reject(error)
})
 
export default service

在路由跳轉時撤銷所有請求

在路由文件index.ts中加入

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from '@/views/Login/Login.vue'
//引入在axios暴露出的clearPending函數
import { clearPending } from "@/api/axios"
 
....
....
....
 
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
 
router.beforeEach((to, from, next) => {
  //在跳轉路由之前,先清除所有的請求
  clearPending()
  // ...
  next()
})
 
export default router

使用封裝的axios請求庫

封裝響應格式

?
1
2
3
4
5
6
7
8
9
10
// 接口響應通過格式
export interface HttpResponse {
  status: number
  statusText: string
  data: {
    code: number
    desc: string
    [key: string]: any
  }
}

封裝接口方法

舉個栗子,進行封裝User接口,代碼如下~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import Axios from './axios'
import { HttpResponse } from '@/@types'
/**
 * @interface loginParams -登錄參數
 * @property {string} username -用戶名
 * @property {string} password -用戶密碼
 */
interface LoginParams {
  username: string
  password: string
}
//封裝User類型的接口方法
export class UserService {
  /**
   * @description 查詢User的信息
   * @param {number} teamId - 所要查詢的團隊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
      },
    })
  }
}

項目中進行使用

代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<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>

到此這篇關于Vue3+TypeScript封裝axios并進行請求調用的實現的文章就介紹到這了,更多相關Vue3+TypeScript封裝axios內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://segmentfault.com/a/1190000039806000

延伸 · 閱讀

精彩推薦
  • vue.jsVue中引入svg圖標的兩種方式

    Vue中引入svg圖標的兩種方式

    這篇文章主要給大家介紹了關于Vue中引入svg圖標的兩種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的...

    十里不故夢10222021-12-31
  • vue.jsVue2.x-使用防抖以及節流的示例

    Vue2.x-使用防抖以及節流的示例

    這篇文章主要介紹了Vue2.x-使用防抖以及節流的示例,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下...

    Kyara6372022-01-25
  • vue.js詳解vue 表單綁定與組件

    詳解vue 表單綁定與組件

    這篇文章主要介紹了vue 表單綁定與組件的相關資料,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下...

    Latteitcjz6432022-02-12
  • vue.js梳理一下vue中的生命周期

    梳理一下vue中的生命周期

    看過很多人講vue的生命周期,但總是被繞的云里霧里,尤其是自學的同學,可能js的基礎也不是太牢固,聽起來更是吃力,那我就已個人之淺見,以大白話...

    CRMEB技術團隊7992021-12-22
  • vue.jsVue項目中實現帶參跳轉功能

    Vue項目中實現帶參跳轉功能

    最近做了一個手機端系統,其中遇到了父頁面需要攜帶參數跳轉至子頁面的問題,現已解決,下面分享一下實現過程,感興趣的朋友一起看看吧...

    YiluRen丶4302022-03-03
  • vue.js用vite搭建vue3應用的實現方法

    用vite搭建vue3應用的實現方法

    這篇文章主要介紹了用vite搭建vue3應用的實現方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下...

    Asiter7912022-01-22
  • vue.jsVue多選列表組件深入詳解

    Vue多選列表組件深入詳解

    這篇文章主要介紹了Vue多選列表組件深入詳解,這個是vue的基本組件,有需要的同學可以研究下...

    yukiwu6752022-01-25
  • vue.jsVue2.x 項目性能優化之代碼優化的實現

    Vue2.x 項目性能優化之代碼優化的實現

    這篇文章主要介紹了Vue2.x 項目性能優化之代碼優化的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋...

    優小U9632022-02-21
主站蜘蛛池模板: 亚洲免费小视频 | 国产精品福利在线观看免费不卡 | 日韩免费高清完整版 | 久热这里只有精品99国产6 | 久久高清一级毛片 | 亚洲国产欧美久久香综合 | 成年无限观看onlyfans | 美女班主任下面好爽好湿好紧 | 日韩一级生活片 | 四虎国产精品免费久久久 | 5g996未满十八 | 国产日韩一区二区 | 久久99re热在线观看视频 | 四虎最新免费网址 | 日本成年片高清在线观看 | 欧美vpswindows | 奇米影视在线视频8888 | 男人看的网址 | 无码人妻精品一区二区蜜桃在线看 | 婷婷99视频精品全部在线观看 | 成人午夜在线视频 | 被巨大黑人的翻白眼 | 卫生间被教官做好爽HH视频 | 秋霞一级黄色片 | 2019nv天堂| 美女福利视频网站 | 韩国甜性涩爱免费观看 | 青青青手机在线观看 | 四虎精品永久免费 | 男公厕里同性做爰 | 日韩欧美国产综合精品 | 交换年轻夫妇HD中文字幕 | 国产在线麻豆波多野结衣 | 关晓彤一级做a爰片性色毛片 | 51国产午夜精品免费视频 | 亚洲狠狠婷婷综合久久蜜桃 | www.麻豆| 国产成人精品福利色多多 | 久久综合视频网站 | 91亚洲精品久久91综合 | 国内外精品免费视频 |