国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Vite4+Typescript+Vue3+Pinia 從零搭建(7) - request封裝

這篇具有很好參考價值的文章主要介紹了Vite4+Typescript+Vue3+Pinia 從零搭建(7) - request封裝。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

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

安裝

npm i axios

封裝

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

1. status.ts 文件主要是封裝狀態(tài)碼

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 = '網(wǎng)關錯誤!請您稍后重試'
      break
    case 503:
      message = '服務不可用!請您稍后重試'
      break
    case 504:
      message = '網(wǎng)關超時!請您稍后重試'
      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,請求需要傳入的參數(shù)類型為 AxiosRequestConfig,響應的數(shù)據(jù)類型為 AxiosResponse,InternalAxiosRequestConfig 繼承于 AxiosRequestConfig
 */
import axios, { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ErrMessage } from './status'

// 自定義請求返回數(shù)據(jù)的類型
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指代加載動畫狀態(tài)

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

  // 類型參數(shù)的作用,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
        // 根據(jù)不同狀態(tài)碼,返回不同信息
        const messageStr = response ? ErrMessage(response.status) : message || '請求失敗,請重試'
        window.alert(messageStr)
        return Promise.reject(err)
      }
    )
    /**
     * 使用通用實例里的攔截,兩個攔截都會生效,返回值以后一個執(zhí)行的為準
     */
    // 請求攔截
    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 主要是創(chuàng)建 Request 實例

/**
 * 創(chuàng)建實例,可以多個,當你需要請求多個不同域名的接口時
 */
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)
    }
  }
})

// 創(chuàng)建其他示例,然后導出
// 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 按鈕,即可看到請求。
Vite4+Typescript+Vue3+Pinia 從零搭建(7) - request封裝

說明

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

1. 為什么要使用 InternalAxiosRequestConfig

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

2. Request 里的 config 參數(shù)

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

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

3. 總結下 request/index.ts 和 api/login.ts 里的參數(shù)有什么不同

request/index.ts 里可以建多個實例,一般以 baseURL 來判斷是否要多個,它的參數(shù)是當前url下的通用參數(shù),攔截規(guī)則也是;
api/login.ts 是具體的請求,它的大部分參數(shù)是url和請求傳參。同一個 baseURL 下有的請求有特殊的要求,那你就可以去加一些參數(shù)。
總的來說,request/index.ts 是對 baseURL 一樣的請求的封裝,request/request.ts 是對所有請求的封裝文章來源地址http://www.zghlxwxcb.cn/news/detail-760467.html

4. 優(yōu)化

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

到了這里,關于Vite4+Typescript+Vue3+Pinia 從零搭建(7) - request封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包