日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vite4+Typescript+Vue3+Pinia 从零搭建(7) - request封装

發布時間:2023/12/24 vue 29 coder
生活随笔 收集整理的這篇文章主要介紹了 Vite4+Typescript+Vue3+Pinia 从零搭建(7) - request封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目代碼同步至碼云 weiz-vue3-template
基于 axios 封裝請求,支持多域名請求地址

安裝

npm i axios

封裝

utils 目錄下新建 request 文件夾,并新建 index.tsrequest.tsstatus.ts 文件。

1. status.ts 文件主要是封裝狀態碼

export const ErrMessage = (status: number | string): string => {
  let message: string = ''
  switch (status) {
    case 400:
      message = '請求錯誤!請您稍后重試'
      break
    case 401:
      message = '未授權!請您重新登錄'
      break
    case 403:
      message = '當前賬號無訪問權限!'
      break
    case 404:
      message = '訪問的資源不存在!請您稍后重試'
      break
    case 405:
      message = '請求方式錯誤!請您稍后重試'
      break
    case 408:
      message = '請求超時!請您稍后重試'
      break
    case 500:
      message = '服務異常!請您稍后重試'
      break
    case 501:
      message = '不支持此請求!請您稍后重試'
      break
    case 502:
      message = '網關錯誤!請您稍后重試'
      break
    case 503:
      message = '服務不可用!請您稍后重試'
      break
    case 504:
      message = '網關超時!請您稍后重試'
      break
    default:
      message = '請求失敗!請您稍后重試'
  }
  return message
}

此時,eslint會報 switch 前面的空格錯誤,需要修改 .eslintrc.cjs 里的 indent,修改后,錯誤消失。

rules: {
  // Switch語句 https://zh-hans.eslint.org/docs/latest/rules/indent#switchcase
  indent: ['error', 2, { SwitchCase: 1 }]
}

2. request.ts 主要是封裝 axios

/**
 * 封裝axios
 * axios 實例的類型為 AxiosInstance,請求需要傳入的參數類型為 AxiosRequestConfig,響應的數據類型為 AxiosResponse,InternalAxiosRequestConfig 繼承于 AxiosRequestConfig
 */
import axios, { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ErrMessage } from './status'

// 自定義請求返回數據的類型
interface Data<T> {
  data: T
  code: string
  success: boolean
}

// 擴展 InternalAxiosRequestConfig,讓每個請求都可以控制是否要loading
interface RequestInternalAxiosRequestConfig extends InternalAxiosRequestConfig {
  showLoading?: boolean
}

// 攔截器
interface InterceptorHooks {
  requestInterceptor?: (config: RequestInternalAxiosRequestConfig) => RequestInternalAxiosRequestConfig
  requestInterceptorCatch?: (error: any) => any
  responseInterceptor?: (response: AxiosResponse) => AxiosResponse
  responseInterceptorCatch?: (error: any) => any
}
// 擴展 AxiosRequestConfig,showLoading 給實例默認增加loading,interceptorHooks 攔截
interface RequestConfig extends AxiosRequestConfig {
  showLoading?: boolean
  interceptorHooks?: InterceptorHooks
}

class Request {
  config: RequestConfig
  instance: AxiosInstance
  loading?: boolean // 用loading指代加載動畫狀態

  constructor(options: RequestConfig) {
    this.config = options
    this.instance = axios.create(options)
    this.setupInterceptor()
  }

  // 類型參數的作用,T決定AxiosResponse實例中data的類型
  request<T = any>(config: RequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, Data<T>>(config)
        .then((res) => {
          resolve(res.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 封裝常用方法
  get<T = any>(url: string, params?: object, _object = {}): Promise<T> {
    return this.request({ url, params, ..._object, method: 'GET' })
  }

  post<T = any>(url: string, params?: object, _object = {}): Promise<T> {
    return this.request({ url, params, ..._object, method: 'POST' })
  }

  delete<T = any>(url: string, params?: object, _object = {}): Promise<T> {
    return this.request({ url, params, ..._object, method: 'DELETE' })
  }

  patch<T = any>(url: string, params?: object, _object = {}): Promise<T> {
    return this.request({ url, params, ..._object, method: 'PATCH' })
  }

  put<T = any>(url: string, params?: object, _object = {}): Promise<T> {
    return this.request({ url, params, ..._object, method: 'PUT' })
  }

  // 自定義攔截器 https://axios-http.com/zh/docs/interceptors
  setupInterceptor(): void {
    /**
     * 通用攔截
     */
    this.instance.interceptors.request.use((config: RequestInternalAxiosRequestConfig) => {
      if (config.showLoading) {
        // 加載loading動畫
        this.loading = true
      }
      return config
    })
    // 響應后關閉loading
    this.instance.interceptors.response.use(
      (res) => {
        if (this.loading) this.loading = false
        return res
      },
      (err) => {
        const { response, message } = err
        if (this.loading) this.loading = false
        // 根據不同狀態碼,返回不同信息
        const messageStr = response ? ErrMessage(response.status) : message || '請求失敗,請重試'
        window.alert(messageStr)
        return Promise.reject(err)
      }
    )
    /**
     * 使用通用實例里的攔截,兩個攔截都會生效,返回值以后一個執行的為準
     */
    // 請求攔截
    this.instance.interceptors.request.use(
      this.config?.interceptorHooks?.requestInterceptor,
      this.config?.interceptorHooks?.requestInterceptorCatch
    )
    // 響應攔截
    this.instance.interceptors.response.use(
      this.config?.interceptorHooks?.responseInterceptor,
      this.config?.interceptorHooks?.responseInterceptorCatch
    )
  }
}

export default Request

3. index.ts 主要是創建 Request 實例

/**
 * 創建實例,可以多個,當你需要請求多個不同域名的接口時
 */
import Request from './request'
import { getToken } from '@/utils/auth'

const defRequest = new Request({
  // 這里用 Easy Mock 模擬了真實接口
  baseURL: 'https://mock.mengxuegu.com/mock/65421527a6dde808a695e96d/official/',
  timeout: 5000,
  showLoading: true,
  interceptorHooks: {
    requestInterceptor: (config) => {
      const token = getToken()
      if (token) {
        config.headers.Authorization = token
      }
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res.data
    },
    responseInterceptorCatch: (err) => {
      return Promise.reject(err)
    }
  }
})

// 創建其他示例,然后導出
// const otherRequest = new Request({...})

export { defRequest }

使用

src 目錄下新建 api 文件夾,并新建 login.ts

1. login.ts

import { defRequest } from '../utils/request'

export const loginApi = (params: any) => {
  // 設置 showLoading,timeout 會覆蓋index.ts里的默認值
  return defRequest.post<any>('/login', params, { showLoading: false, timeout: 1000 })
}

2. 修改 login.vue

<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@store/user'
import { loginApi } from '@/api/login'

defineOptions({
  name: 'V-login'
})

const userStore = useUserStore()
const { userInfo, token } = storeToRefs(userStore)
let userName = ref(userInfo.value.name)
let userToken = ref(token)

const updateUserName = () => {
  userStore.setUserInfo({
    name: userName.value
  })
}
const updateUserToken = () => {
  userStore.setToken(userToken.value)
}

const login = () => {
  loginApi({
    name: userName.value
  })
    .then((res) => {
      userName.value = res.name
      userToken.value = res.token
      updateUserToken()
    })
    .catch((err) => {
      console.log(err)
    })
}
</script>

<template>
  <div>login page</div>
  name:
  <input type="text" v-model="userName" @input="updateUserName" />
  <br />
  token:
  <input type="text" v-model="userToken" />
  <hr />
  <button @click="login">login</button>
</template>

<style scoped></style>

點擊 login 按鈕,即可看到請求。

說明

對于 axios 的封裝和使用,這里要說明幾點:

1. 為什么要使用 InternalAxiosRequestConfig

axios 源碼有修改,攔截器傳入和返回的參數不再是 AxiosRequestConfig,而是這個新類型 InternalAxiosRequestConfig
想要具體了解,可以查看這篇博文 https://blog.csdn.net/huangfengnt/article/details/131490913

2. Request 里的 config 參數

constructor 里的 this.config 會接受所有實例參數,所以通用實例攔截里使用的是 this.config?.xxx
通用攔截里使用的是 config.showLoading,而不是 this.config.showLoading,是為了我們在實際的 api/login.ts 里可以再傳入 showLoading,以滿足我們單個請求的要求。而通過 this.config 里獲取的配置是 request/index.ts 里傳入的配置。在 config.showLoading 之前我們可以打印下這兩個 configconsole.log(this.config, config) 結果如下:

如果在 login.ts 里不傳入 showLoading,那么 config.showLoading 會去拿通用實例 request/index.ts 里的 showLoading
** 當然如果不需要全局加載動畫,整個 loading 也都可以去掉 **

3. 總結下 request/index.tsapi/login.ts 里的參數有什么不同

request/index.ts 里可以建多個實例,一般以 baseURL 來判斷是否要多個,它的參數是當前url下的通用參數,攔截規則也是;
api/login.ts 是具體的請求,它的大部分參數是url和請求傳參。同一個 baseURL 下有的請求有特殊的要求,那你就可以去加一些參數。
總的來說,request/index.ts 是對 baseURL 一樣的請求的封裝,request/request.ts 是對所有請求的封裝

4. 優化

  • 因為 Easy Mock 的接口支持跨域,所以沒有配到代理里去,如果是正常開發接口,還需要修改 vite.config.ts 里的 proxy。不過我們之前的教程里已有代理配置說明,這里便不再贅述
  • baseURL 還可以放在 env 變量里,以便區分開發環境和生產環境
  • ** 刪除 loading,這里只是為了提供一種思路?? **

總結

以上是生活随笔為你收集整理的Vite4+Typescript+Vue3+Pinia 从零搭建(7) - request封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。