gmnon.cn-疯狂蹂躏欧美一区二区精品,欧美精品久久久久a,高清在线视频日韩欧美,日韩免费av一区二区

站長資訊網(wǎng)
最全最豐富的資訊網(wǎng)站

聊聊vite+vue3.0+ts中如何封裝axios?

聊聊vite+vue3.0+ts中如何封裝axios?

目前,關(guān)于vue中使用axios的作為前端和后端接口交互工具的用法文章,網(wǎng)絡(luò)某博客上數(shù)不勝數(shù)。因為項目從0到1開始需要基于vite+vue3.0+ts中封裝axios,所以今天讓小編來給大家安排axios整合vite+vue3.0+ts的具體封裝步驟。記錄一下自己封裝步驟,跟著我的步伐,擼起來。。。(學(xué)習(xí)視頻分享:vue視頻教程)

以下內(nèi)容均基于下方視頻完結(jié)后的擴展:

2021最新最詳細的Vite+vue3+Volar+Ts+Element-plus框架學(xué)習(xí)項目視頻

1、安裝axios

npm i axios

注意:這里的安裝命令就是默認安裝最新版本的axios

2、封裝請求錯誤代碼提示error-code-type.ts

  • 代碼如下:
export const errorCodeType = function(code:string):string{     let errMessage:string = "未知錯誤"     switch (code) {         case 400:          errMessage = '錯誤的請求'          break          case 401:          errMessage = '未授權(quán),請重新登錄'          break         case 403:          errMessage = '拒絕訪問'          break          case 404:          errMessage = '請求錯誤,未找到該資源'          break          case 405:          errMessage = '請求方法未允許'          break          case 408:          errMessage = '請求超時'          break          case 500:          errMessage = '服務(wù)器端出錯'          break          case 501:          errMessage = '網(wǎng)絡(luò)未實現(xiàn)'          break          case 502:          errMessage = '網(wǎng)絡(luò)錯誤'          break          case 503:          errMessage = '服務(wù)不可用'          break          case 504:          errMessage = '網(wǎng)絡(luò)超時'          break          case 505:          errMessage = 'http版本不支持該請求'          break          default:          errMessage = `其他連接錯誤 --${code}`     }     return errMessage }

3、封裝request.ts

這里用到的element-plus大家可以參考其官網(wǎng)安裝即可,傳送門:

element-plus官網(wǎng)

安裝命令: npm install element-plus --save
  • 代碼如下:
import axios from 'axios'; import { errorCodeType } from '@/script/utils/error-code-type'; import { ElMessage, ElLoading } from 'element-plus';  // 創(chuàng)建axios實例 const service = axios.create({     // 服務(wù)接口請求     baseURL: import.meta.env.VITE_APP_BASE_API,     // 超時設(shè)置     // timeout: 15000,     headers:{'Content-Type':'application/json;charset=utf-8'} })  let loading:any; //正在請求的數(shù)量 let requestCount:number = 0 //顯示loading const showLoading = () => {     if (requestCount === 0 && !loading) {         //加載中顯示樣式可以自行修改         loading = ElLoading.service({             text: "拼命加載中,請稍后...",             background: 'rgba(0, 0, 0, 0.7)',             spinner: 'el-icon-loading',         })     }     requestCount++; } //隱藏loading const hideLoading = () => {     requestCount--     if (requestCount == 0) {         loading.close()     } }  // 請求攔截 service.interceptors.request.use(config => {     showLoading()     // 是否需要設(shè)置 token放在請求頭     // config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個請求攜帶自定義token 請根據(jù)實際情況自行修改     // get請求映射params參數(shù)     if (config.method === 'get' && config.params) {         let url = config.url + '?';         for (const propName of Object.keys(config.params)) {             const value = config.params[propName];             var part = encodeURIComponent(propName) + "=";             if (value !== null && typeof(value) !== "undefined") {                  // 對象處理                 if (typeof value === 'object') {                     for (const key of Object.keys(value)) {                         let params = propName + '[' + key + ']';                         var subPart = encodeURIComponent(params) + "=";                         url += subPart + encodeURIComponent(value[key]) + "&";                     }                 } else {                     url += part + encodeURIComponent(value) + "&";                 }             }         }         url = url.slice(0, -1);         config.params = {};         config.url = url;     }     return config }, error => {     console.log(error)     Promise.reject(error) })  // 響應(yīng)攔截器 service.interceptors.response.use((res:any) => {         hideLoading()         // 未設(shè)置狀態(tài)碼則默認成功狀態(tài)         const code = res.data['code'] || 200;         // 獲取錯誤信息         const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default')         if(code === 200){             return Promise.resolve(res.data)         }else{             ElMessage.error(msg)             return Promise.reject(res.data)         }     },     error => {         console.log('err' + error)         hideLoading()         let { message } = error;         if (message == "Network Error") {             message = "后端接口連接異常";         }         else if (message.includes("timeout")) {             message = "系統(tǒng)接口請求超時";         }         else if (message.includes("Request failed with status code")) {             message = "系統(tǒng)接口" + message.substr(message.length - 3) + "異常";         }         ElMessage.error({             message: message,             duration: 5 * 1000         })         return Promise.reject(error)     } )  export default service;

4、自動導(dǎo)入vue3相關(guān)函數(shù)(auto-imports.d.ts)

  • auto-imports.d.ts放在src目錄下
  • 注意:需要安裝yarn add unplugin-auto-import或者npm i unplugin-auto-import -D
  • 安裝完重啟項目
  • 代碼如下:
declare global {   const computed: typeof import('vue')['computed']   const createApp: typeof import('vue')['createApp']   const customRef: typeof import('vue')['customRef']   const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']   const defineComponent: typeof import('vue')['defineComponent']   const effectScope: typeof import('vue')['effectScope']   const EffectScope: typeof import('vue')['EffectScope']   const getCurrentInstance: typeof import('vue')['getCurrentInstance']   const getCurrentScope: typeof import('vue')['getCurrentScope']   const h: typeof import('vue')['h']   const inject: typeof import('vue')['inject']   const isReadonly: typeof import('vue')['isReadonly']   const isRef: typeof import('vue')['isRef']   const markRaw: typeof import('vue')['markRaw']   const nextTick: typeof import('vue')['nextTick']   const onActivated: typeof import('vue')['onActivated']   const onBeforeMount: typeof import('vue')['onBeforeMount']   const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']   const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']   const onDeactivated: typeof import('vue')['onDeactivated']   const onErrorCaptured: typeof import('vue')['onErrorCaptured']   const onMounted: typeof import('vue')['onMounted']   const onRenderTracked: typeof import('vue')['onRenderTracked']   const onRenderTriggered: typeof import('vue')['onRenderTriggered']   const onScopeDispose: typeof import('vue')['onScopeDispose']   const onServerPrefetch: typeof import('vue')['onServerPrefetch']   const onUnmounted: typeof import('vue')['onUnmounted']   const onUpdated: typeof import('vue')['onUpdated']   const provide: typeof import('vue')['provide']   const reactive: typeof import('vue')['reactive']   const readonly: typeof import('vue')['readonly']   const ref: typeof import('vue')['ref']   const resolveComponent: typeof import('vue')['resolveComponent']   const shallowReactive: typeof import('vue')['shallowReactive']   const shallowReadonly: typeof import('vue')['shallowReadonly']   const shallowRef: typeof import('vue')['shallowRef']   const toRaw: typeof import('vue')['toRaw']   const toRef: typeof import('vue')['toRef']   const toRefs: typeof import('vue')['toRefs']   const triggerRef: typeof import('vue')['triggerRef']   const unref: typeof import('vue')['unref']   const useAttrs: typeof import('vue')['useAttrs']   const useCssModule: typeof import('vue')['useCssModule']   const useCssVars: typeof import('vue')['useCssVars']   const useSlots: typeof import('vue')['useSlots']   const watch: typeof import('vue')['watch']   const watchEffect: typeof import('vue')['watchEffect'] } export {}

5、自動導(dǎo)入Element Plus 相關(guān)函數(shù)(components.d.ts)

  • 注意:需要安裝npm i unplugin-vue-components -D或者yarn add unplugin-vue-components
  • 安裝完重啟項目
import '@vue/runtime-core'  declare module '@vue/runtime-core' {   export interface GlobalComponents {     ElCard: typeof import('element-plus/es')['ElCard']     ElCol: typeof import('element-plus/es')['ElCol']     ElContainer: typeof import('element-plus/es')['ElContainer']     ElFooter: typeof import('element-plus/es')['ElFooter']     ElHeader: typeof import('element-plus/es')['ElHeader']     ElMain: typeof import('element-plus/es')['ElMain']     ElOption: typeof import('element-plus/es')['ElOption']     ElPagination: typeof import('element-plus/es')['ElPagination']     ElRadioButton: typeof import('element-plus/es')['ElRadioButton']     ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']     ElRow: typeof import('element-plus/es')['ElRow']     ElSelect: typeof import('element-plus/es')['ElSelect']     ElTable: typeof import('element-plus/es')['ElTable']     ElTableColumn: typeof import('element-plus/es')['ElTableColumn']     Loading: typeof import('element-plus/es')['ElLoadingDirective']   } }  export {}

6、vite.config.ts文件配置

  • 注意:需要安裝npm i unplugin-icons或者yarn add unplugin-icons
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import Icons from "unplugin-icons/vite"; import IconsResolver from "unplugin-icons/resolver"; import AutoImport from "unplugin-auto-import/vite"; import Components from "unplugin-vue-components/vite"; import { ElementPlusResolver } from "unplugin-vue-components/resolvers"; import { loadEnv } from 'vite'; import path from 'path'; // 路徑 const pathSrc = path.resolve(__dirname,'src')  // https://vitejs.dev/config/ export default({ command, mode }) => {     return defineConfig({         plugins: [             vue(),             AutoImport({                 // Auto import functions from Vue, e.g. ref, reactive, toRef...                 // 自動導(dǎo)入 Vue 相關(guān)函數(shù),如:ref, reactive, toRef 等                 imports: ["vue"],                  // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)                 // 自動導(dǎo)入 Element Plus 相關(guān)函數(shù),如:ElMessage, ElMessageBox... (帶樣式)                 resolvers: [                     ElementPlusResolver(),                      // Auto import icon components                     // 自動導(dǎo)入圖標(biāo)組件                     IconsResolver({                         prefix: "Icon",                     }),                 ],                  dts: path.resolve(pathSrc, "auto-imports.d.ts"),             }),                          // 自動導(dǎo)入 Element Plus 組件             Components({                 resolvers: [                     // Auto register icon components                     // 自動注冊圖標(biāo)組件                     IconsResolver({                         enabledCollections: ["ep"],                     }),                     // Auto register Element Plus components                                         ElementPlusResolver(),                 ],                  dts: path.resolve(pathSrc, "components.d.ts"),             }),             // 圖標(biāo)             Icons({                 autoInstall: true,             }),         ],         server:{             host: '127.0.0.1',             //port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),             port: 3000,             strictPort: true, // 端口被占用直接退出             https: false,             open: true,// 在開發(fā)服務(wù)器啟動時自動在瀏覽器中打開應(yīng)用程序             proxy: {                 // 字符串簡寫寫法                 '^/api': {                     target: mode==='development'?loadEnv(mode, process.cwd()).VITE_APP_DEV_URL:loadEnv(mode, process.cwd()).VITE_APP_PROD_URL,                     changeOrigin: true,                     rewrite: (path) => path.replace(/^/api/, '')                 }             },             hmr:{                 overlay: false // 屏蔽服務(wù)器報錯             }         },         resolve:{             alias:{                 '@': pathSrc,             }         },         css:{             // css預(yù)處理器             /*preprocessorOptions: {                 scss: {                     additionalData: '@import "@/assets/styles/global.scss";'                 }             }*/              preprocessorOptions: {                less: {                  charset: false,                  additionalData: '@import "./src/assets/style/global.less";',                 },             },         },         build:{             chunkSizeWarningLimit: 1500, // 分塊打包,分解塊,將大塊分解成更小的塊             rollupOptions: {                 output:{                     manualChunks(id) {                         if (id.includes('node_modules')) {                             return id.toString().split('node_modules/')[1].split('/')[0].toString();                         }                     }                 }             }         }     }) }

7、使用axios封裝

完整的環(huán)境變量配置文件.env.production和.env.development

7.1、項目根目錄的development文件內(nèi)容如下

# 開發(fā)環(huán)境 VITE_APP_TITLE = "阿綿"  # 端口號  VITE_APP_PORT = "3000"  # 請求接口  VITE_APP_DEV_URL = "http://localhost:8088"  # 前綴  VITE_APP_BASE_API = "/api"

7.2、項目根目錄下的production文件內(nèi)容如下

# 開發(fā)環(huán)境  VITE_APP_TITLE = "阿綿"  # 端口號  VITE_APP_PORT = "3000"  # 請求接口  VITE_APP_DEV_URL = "http://localhost:8088"  # 前綴  VITE_APP_BASE_API = "/api"

8、在任何vue文件內(nèi)使用接口:

  • 注意:這里還有一個PageParams全局分頁對象:

  • page-params.ts

  • 代碼如下:

// 全局統(tǒng)一分頁參數(shù)類型聲明  declare interface PageParams {     pageNum: number, pageSize: number, type?: Model, // 可選參數(shù)      readonly sort?: string // 只讀可選參數(shù)  } interface Model { type?: string } export default PageParams;

總結(jié)

本篇討論的主要內(nèi)容是:

  1. axios整合vite+vue3.0+ts的具體封裝步驟,對于細節(jié)方面還沒很細,可以擴展更深入封裝它

(學(xué)習(xí)視頻分享:web前端開發(fā)、編程基礎(chǔ)視頻)

贊(0)
分享到: 更多 (0)
?
網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
gmnon.cn-疯狂蹂躏欧美一区二区精品,欧美精品久久久久a,高清在线视频日韩欧美,日韩免费av一区二区
91精品91久久久中77777老牛| 男人添女人荫蒂免费视频| 激情五月婷婷六月| 91香蕉视频免费看| 亚洲高清视频免费| www.欧美激情.com| www.国产视频.com| 久久成年人网站| 中国 免费 av| 国产激情片在线观看| 激情小视频网站| www.亚洲视频.com| 国产91xxx| 99久久久无码国产精品6| 日韩精品一区二区三区色欲av| 北条麻妃69av| 国产一二三区av| 亚洲午夜精品一区| 青青草视频在线视频| 拔插拔插海外华人免费| 国产精品成人久久电影| 国产美女无遮挡网站| 超碰在线97免费| 五月天av影院| 久色视频在线播放| 亚洲国产精品三区| japanese在线视频| 国产免费黄色av| 黄色一级片免费播放| 欧美这里只有精品| 人人爽人人av| 伊人再见免费在线观看高清版| 国产精品无码人妻一区二区在线| 久久婷婷国产精品| 午夜在线视频免费观看| av天堂永久资源网| 三上悠亚免费在线观看| 久久午夜夜伦鲁鲁一区二区| 欧美一区二区三区综合| 动漫av免费观看| 国产尤物av一区二区三区| 国产一级不卡毛片| 国产免费一区二区三区四在线播放| 黄色一级视频片| 国产又爽又黄ai换脸| 国产熟人av一二三区| 野外做受又硬又粗又大视频√| 91极品视频在线观看| www国产黄色| 女人色极品影院| 在线观看免费不卡av| 99色精品视频| 欧美爱爱视频免费看| 免费在线黄网站| 中文国产在线观看| 成年人三级黄色片| 天天视频天天爽| 国产三级三级三级看三级| a√天堂在线观看| 免费不卡av在线| 国内外成人激情免费视频| 亚洲精品在线网址| 免费看av软件| 三年中国中文在线观看免费播放| 韩国中文字幕av| 在线观看国产一级片| 五月婷婷丁香综合网| 爱爱爱爱免费视频| 午夜免费看毛片| 在线观看日本www| 中文字幕一区二区三区四区在线视频| 欧美精品一区免费| 日本va中文字幕| 黑森林精品导航| 中文字幕亚洲乱码| 17c国产在线| 国产三级精品三级在线| 麻豆三级在线观看| 国产精品探花在线播放| 视色,视色影院,视色影库,视色网 日韩精品福利片午夜免费观看 | 亚洲午夜激情影院| 8x8x华人在线| 国模无码视频一区二区三区| 激情综合在线观看| 亚洲成人av免费看| aaaaaaaa毛片| 成人在线观看你懂的| 凹凸日日摸日日碰夜夜爽1| 日韩av一卡二卡三卡| 日日夜夜精品视频免费观看| 免费拍拍拍网站| 黄色片视频在线| 欧洲美女和动交zoz0z| 男人天堂1024| 午夜大片在线观看| 成人黄色av片| 亚洲成人福利在线| 久久国产精品网| 亚洲va在线va天堂va偷拍| 真实国产乱子伦对白视频| 丰满少妇在线观看| 亚洲 欧美 综合 另类 中字| 国产a级片免费观看| 无颜之月在线看| 狠狠操狠狠干视频| 北条麻妃在线视频观看| 一本—道久久a久久精品蜜桃| 黄色一级片在线看| 大桥未久一区二区三区| 91看片就是不一样| 无码粉嫩虎白一线天在线观看| 亚洲男人天堂av在线| 日本精品免费在线观看| 男人草女人视频| 亚洲精品偷拍视频| 欧美精品久久久久久久久25p| 精品国产一区二区三区无码| 孩娇小videos精品| 国产精品99久久免费黑人人妻| 丁香色欲久久久久久综合网| 免费成人黄色大片| 男女男精品视频站| 黄色免费观看视频网站| 无码人妻精品一区二区蜜桃网站| 天天干天天色天天干| 麻豆av免费在线| 成人在线观看黄| 狠狠爱免费视频| 国产成人久久777777| 成人黄色片视频| 99久久激情视频| 女人另类性混交zo| 日韩手机在线观看视频| 国产精品wwwww| 久久久精品麻豆| 岛国毛片在线播放| 亚洲精品mv在线观看| 色www免费视频| 手机成人av在线| 国产情侣第一页| 亚洲美免无码中文字幕在线| 日韩日韩日韩日韩日韩| 成人在线观看你懂的| 国产精品va无码一区二区| 日韩黄色片视频| 亚洲欧美日韩精品一区| 中文字幕在线视频一区二区| 久久久天堂国产精品| 国产午夜福利在线播放| 乱子伦视频在线看| 日韩不卡的av| 亚洲熟妇无码一区二区三区导航| av女优在线播放| 国内外成人免费在线视频| 欧洲xxxxx| 可以在线看的黄色网址| 在线无限看免费粉色视频| 日韩一级特黄毛片| 看欧美ab黄色大片视频免费 | 第一区免费在线观看| 91免费网站视频| www一区二区www免费| 色免费在线视频| 久久99久久99精品| 中国黄色片免费看| 欧美中日韩在线| 日本 片 成人 在线| 国产精品无码免费专区午夜| 久久国产亚洲精品无码| 国产乱码一区二区三区四区| 亚洲精品久久久久久久蜜桃臀| 亚洲激情在线观看视频| 丁香色欲久久久久久综合网| 青青在线免费观看视频| www.日本少妇| 异国色恋浪漫潭| 色婷婷.com| 污污视频网站免费观看| a级黄色一级片| xxxxxx在线观看| 中文字幕第100页| 丝袜老师办公室里做好紧好爽 | 欧美这里只有精品| 天天色天天综合网| 麻豆传传媒久久久爱| 无码专区aaaaaa免费视频| 无套内谢丰满少妇中文字幕 | 国产偷人视频免费| 国产91porn| 欧美性受xxxxxx黑人xyx性爽| 777777av| 欧美 日本 亚洲| 久久这里只有精品23| 人妻激情另类乱人伦人妻| 免费久久久久久| 在线无限看免费粉色视频| 手机版av在线| 亚洲精品在线视频播放| 日韩av影视大全| 男同互操gay射视频在线看|