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

Vue3和TypeScript下基于Axios的二次封裝教程

這篇具有很好參考價值的文章主要介紹了Vue3和TypeScript下基于Axios的二次封裝教程。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

準(zhǔn)備

截屏2023-05-14 21.10.35.png

  • 創(chuàng)建vue3項目

  • 在 src 的文件下創(chuàng)建 發(fā)送網(wǎng)絡(luò)請求相關(guān)的 文件夾 ??? service

??? service 包含有:

  • index.ts 統(tǒng)一的出口

  • ?? request 用于封裝axios網(wǎng)絡(luò)請求

  • ?? modules 模塊發(fā)送網(wǎng)絡(luò)請求

  • ?? config 配置項

  • 用于測試發(fā)送 網(wǎng)絡(luò)請求的 api
    - 歷史上的今天 https://api.oioweb.cn/api/common/history
    - 每日一句英文 https://api.oioweb.cn/doc/common/OneDayEnglish

  • 推薦使用 直課堂公開的api http://www.zkt-it.com:5050/jiekou/?target_id=001

    • baseURL: http://www.zkt-it.com:5050

?? request

??? index.ts

使用 class把封裝 axios 封裝成一個類,導(dǎo)出這個類

類型問題:

axios.create類型:
截屏2023-05-15 10.28.59.png
攔截器類型問題:
截屏2023-05-14 22.57.56.png

封裝代碼

import axios from 'axios'import type { AxiosInstance } from 'axios'// 攔截器:loading、token、修改配置// AxiosRequestConfig類型中沒有 interceptors 需要擴(kuò)展類型import PKRequestConfig from './type'class PKRequest {
  instance: AxiosInstance  constructor(config: PKRequestConfig) {
    // 每個實例都會 創(chuàng)建axios 
    this.instance = axios.create(config)

    //   實例 全局的攔截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('實例-> 全局的請求成功的攔截:')
        return config      },
      (err) => {
        console.log('實例-> 全局的請求失敗的攔截:')
        return err      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        console.log('實例-> 全局的響應(yīng)成功的攔截:')
        //  res.data => promise的res類型有問題 : 通過泛型解決
        return res      },
      (err) => {
        console.log('實例-> 全局的響應(yīng)失敗的攔截:')
        return err      }
    )
    //   針對特定的pkRequest實例添加攔截
    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessFn,
      config.interceptors?.requestFailedFn    )
    this.instance.interceptors.response.use(
      config.interceptors?.reponseSuccessFn,
      config.interceptors?.reponseFailedFn    )
  }
  // 網(wǎng)絡(luò)請求泛型; 因為promise的成功的回調(diào) 返回的類型 是創(chuàng)建實例時確定的
  // PKRequestConfig<T> : PKRequestConfig中的攔截器 響應(yīng)成功的返回數(shù)據(jù)類型需要和 promise一致
  request<T = any>(config: PKRequestConfig<T>) {
    // 針對網(wǎng)絡(luò)請求 中,有 攔截器
    if (config.interceptors?.requestSuccessFn) {
      // 單次請求的成功攔截
      config.interceptors.requestSuccessFn(config as any)
    }
    // 返回的promise
    return new Promise<T>((resolve, reject) => {
      this.instance        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.reponseSuccessFn) {
            res = config.interceptors.reponseSuccessFn(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }


  get<T = any>(config: PKRequestConfig<T>) {
    return this.request({ ...config, method: 'GET' })
  }
  post<T = any>(config: PKRequestConfig<T>) {
    return this.request({ ...config, method: 'POST' })
  }
  delete<T = any>(config: PKRequestConfig<T>) {
    return this.request({ ...config, method: 'DELETE' })
  }
  put<T = any>(config: PKRequestConfig<T>) {
    return this.request({ ...config, method: 'PUT' })
  }
  patch<T = any>(config: PKRequestConfig<T>) {
    return this.request({ ...config, method: 'PATCH' })
  }}export default PKRequest


import type { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'// 擴(kuò)展 AxiosRequestConfig類型interface PKInterceptors<T = AxiosResponse> {
  requestSuccessFn?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig
  requestFailedFn?: (err: any) => any
  reponseSuccessFn?: (res: T) => T
  reponseFailedFn?: (err: any) => any}interface PKRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
  interceptors?: PKInterceptors<T>}export default PKRequestConfig


?? config

??? index.ts 主要寫配置

export const BASE_URL = 'http://www.zkt-it.com:5050'export const TIME_OUT = 10000// 測試登錄獲取tokenexport const BASE_URL2 = 'http://codercba.com:5000'


?? index.ts

創(chuàng)建 PKRequest 的實例。實例可以有多個
例如:

import PKRequest from './request'import { BASE_URL, TIME_OUT } from './config/index'// pkRequest實例const pkRequest = new PKRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT})// 實例2export const pkRequest2 = new PKRequest({
  baseURL: 'https://api.oioweb.cn/api/common',
  timeout: 8000,
  // 單獨(dú)的攔截器
  // AxiosRequestConfig類型中沒有 interceptors
  interceptors: {
    requestSuccessFn: (config) => {
      console.log('pkRequest2單獨(dú)攔截器:請求成功的攔截')
      return config    },
    requestFailedFn: (err) => {
      console.log('pkRequest2單獨(dú)攔截器:請求失敗的攔截')
      return err    },
    reponseSuccessFn: (res) => {
      console.log('pkRequest2單獨(dú)攔截器:響應(yīng)成功的攔截')
      return res    },
    reponseFailedFn: (err) => {
      console.log('pkRequest2單獨(dú)攔截器:響應(yīng)失敗的攔截')
      return err    }
  }})// 實例3:登錄 BASE_URL2export const pkRequest3 = new PKRequest({
  baseURL: BASE_URL2,
  timeout: 3000})export default pkRequest


?? module

??? index.ts

import('./home')import('./year')import('./gettest')import('./login')


??? home.ts

import pkRequest from '..'// home.ts // 根據(jù)請求數(shù)據(jù)設(shè)置數(shù)據(jù)類型interface INews {
  data: any[]
  status: number
  statusText: string
  config: object
  headers: any
  request: any}pkRequest  .request<INews>({
    url: '/news'
  })
  .then((res) => {
    // 通過泛型設(shè)置,此時的res類型為 INews
    console.log('pkRequest1:新聞', res.data, res.status)
  })pkRequest  .request({ //沒有特別寫類型,則是泛型的默認(rèn)值 any
    url: '/mingxing',
    interceptors: {
      requestSuccessFn: (config) => {
        console.log('/mingxing 請求成功的攔截 :')
        return config      },
      reponseSuccessFn: (res) => {
        console.log('/mingxing 響應(yīng)成功的攔截 :')
        return res      }
    }
  })
  .then((res) => {
    console.log('pkRequest1:明星', res)
  })


??? year.ts

import { pkRequest2 } from '..'// year.tspkRequest2  .request({
    url: '/history'
  })
  .then((res) => {
    console.log('pkRequest2:歷史上的今天', res)
  })


??? login.ts

import { pkRequest3 } from '..'const postLoginRequest = async () => {
  const res = await pkRequest3.post({
    url: '/login',
    data: {
      name: 'coderwhy',
      password: '123456'
    }
  })
  console.log('登錄用戶信息:')
  console.table(res.data.data)}postLoginRequest()


輸出結(jié)果

截屏2023-05-15 10.49.59.png文章來源地址http://www.zghlxwxcb.cn/news/detail-450045.html

到了這里,關(guān)于Vue3和TypeScript下基于Axios的二次封裝教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

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

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Vue3中搜索表單的二次封裝

    最近使用Vue3+ElementPlus開發(fā)項目,從整體上構(gòu)思組件的封裝。能寫成組件的內(nèi)容都進(jìn)行封裝,方便多個地方使用。 受AntDesign的啟發(fā),在項目中有搜索表單+table+分頁的地方可以封裝為一個組件,只需要對組件傳入table的列,組成一個配置項,通過配置可以顯示搜索表單、table項的

    2024年02月11日
    瀏覽(85)
  • axios的二次封裝

    axios的二次封裝

    1 axios是干什么的? XMLHttpRequest、jq、fetch、axios都是用來向服務(wù)器端發(fā)送請求,并獲得響應(yīng) 2 為什么要進(jìn)行二次封裝axios? 為了封裝請求攔截器,響應(yīng)攔截器 請求攔截器:可以在發(fā)送請求之前可以處理一些業(yè)務(wù) 響應(yīng)攔截器:當(dāng)服務(wù)器數(shù)據(jù)返回以后,可以處理一些事情 在src下創(chuàng)

    2023年04月12日
    瀏覽(97)
  • vue3富文本編輯器的二次封裝開發(fā)-Tinymce

    vue3富文本編輯器的二次封裝開發(fā)-Tinymce

    歡迎點(diǎn)擊領(lǐng)取 -《前端開發(fā)面試題進(jìn)階秘籍》:前端登頂之巔-最全面的前端知識點(diǎn)梳理總結(jié) 專享鏈接 簡介 1、安裝:pnpm add tinymce @tinymce/tinymce-vue === Vue3 + tinymce + @tinymce/tinymce-vue 2、功能實現(xiàn)圖片上傳、基金卡片插入、收益卡片插入、源代碼復(fù)用、最大長度限制、自定義表情包

    2024年02月07日
    瀏覽(101)
  • 關(guān)于axios的二次封裝

    @1 第一步 我們一般都會先導(dǎo)入axios ? ? ? ? import axios from ‘a(chǎn)xios’ @2?第二步 創(chuàng)建axios的實例 可以同時創(chuàng)建多個實例 每個實例配置不同 ? ? ? ? const http?= axios.create( {? ? ? ? ? ????????// 這里面可以做一些基礎(chǔ)的配置 比如基礎(chǔ)路徑 ,axios 請求超時的時間 ? ? ? ? ???

    2024年02月03日
    瀏覽(93)
  • Axios的二次封裝(簡單易懂)

    是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端 簡單的理解就是ajax的封裝 在使用Vue.js框架開發(fā)前端項目時 會經(jīng)常發(fā)送ajax請求服務(wù)端接口 在開發(fā)過程中 需要對axios進(jìn)一步封裝 方便在項目中的使用 從瀏覽器中創(chuàng)建 XMLHttpRequest 從 node.js 發(fā)出 http 請求 支持 Promise API 攔截請求

    2023年04月09日
    瀏覽(241)
  • vue3 element-plus el-form的二次封裝

    form表單的二次封裝 vue3 element-plus el-form的二次封裝 屬性名 類型 默認(rèn)值 說明 data Array [] 頁面展示數(shù)據(jù)內(nèi)容 onChange Function false 表單事件 bindProps Object {} 表單屬性 formRef Object {} 表單ref ruleForm Object {} 數(shù)據(jù)

    2024年02月13日
    瀏覽(103)
  • 個人博客-SpringBoot+Vue3項目實戰(zhàn)(6)- 二次封裝Axios

    個人博客-SpringBoot+Vue3項目實戰(zhàn)(6)- 二次封裝Axios

    在上文中,我們封裝了統(tǒng)一的后端數(shù)據(jù)返回結(jié)果,有了標(biāo)準(zhǔn)化的接口數(shù)據(jù),我們就可以針對它,在前端發(fā)送接收時,進(jìn)行預(yù)處理。 通常在一個企業(yè)級或者個人開源的項目中, Axios 會被二次封裝。 二次封裝的好處有哪些呢? 統(tǒng)一 url 配置 統(tǒng)一 api 請求 request (請求)攔截器,例

    2024年02月06日
    瀏覽(95)
  • Vue組件封裝:基于Vue3+wangeditor富文本組件二次封裝

    Vue組件封裝:基于Vue3+wangeditor富文本組件二次封裝

    1.簡介 ? ? ? ? 開源 Web 富文本編輯器,開箱即用,配置簡單。一個產(chǎn)品的價值,就在于解決用戶的問題,提高效率、降低成本、增加穩(wěn)定性和擴(kuò)展性。wangEditor 不是為了做而做,也不是單純的模仿誰,而是經(jīng)過上述問題分析之后,給出一個系統(tǒng)的解決方案。旨在真正去解決用

    2024年04月08日
    瀏覽(96)
  • axios 實戰(zhàn)進(jìn)階練習(xí)( axios 封裝篇)——基于 Vue3 + Node.js + ElementPlus 實現(xiàn)的聯(lián)系人列表管理后臺的 axios 封裝實戰(zhàn)

    axios 實戰(zhàn)進(jìn)階練習(xí)( axios 封裝篇)——基于 Vue3 + Node.js + ElementPlus 實現(xiàn)的聯(lián)系人列表管理后臺的 axios 封裝實戰(zhàn)

    在之前的文章 axios 實戰(zhàn)進(jìn)階練習(xí)——基于 Vue3 + Node.js + ElementPlus 實現(xiàn)的聯(lián)系人列表管理后臺 中,我們完成了這個 基于 Vue3 + Node.js + ElementPlus 實現(xiàn)的聯(lián)系人列表管理后臺 的項目,其中項目的后端接口是用 Node.js 編寫的,通過 axios 來獲取接口,所以這篇文章我們來對這個 axi

    2024年02月11日
    瀏覽(360)
  • 基于Vant組件庫二次封裝組件(TS+Vue3.x環(huán)境)

    基于Vant組件庫二次封裝組件(TS+Vue3.x環(huán)境)

    1. 今天的需求是封裝一個 Navigation Bar 導(dǎo)航欄組件,目的是給到App幾乎所有的頁面復(fù)用: ?? ? 2. 因為之前的項目里使用過Vant組件庫,筆者第一時間想到了Vant組件庫中的 NavBar 組件,和當(dāng)前App的需求匹配度很高。Vant組件庫的 NavBar 組件: 3. 相信你也發(fā)現(xiàn)了,Vant組件庫默認(rèn)主題

    2023年04月18日
    瀏覽(100)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包