久久精品五月,日韩不卡视频在线观看,国产精品videossex久久发布 ,久久av综合

站長資訊網
最全最豐富的資訊網站

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

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

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

以下內容均基于下方視頻完結后的擴展:

2021最新最詳細的Vite+vue3+Volar+Ts+Element-plus框架學習項目視頻

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 = '未授權,請重新登錄'          break         case 403:          errMessage = '拒絕訪問'          break          case 404:          errMessage = '請求錯誤,未找到該資源'          break          case 405:          errMessage = '請求方法未允許'          break          case 408:          errMessage = '請求超時'          break          case 500:          errMessage = '服務器端出錯'          break          case 501:          errMessage = '網絡未實現'          break          case 502:          errMessage = '網絡錯誤'          break          case 503:          errMessage = '服務不可用'          break          case 504:          errMessage = '網絡超時'          break          case 505:          errMessage = 'http版本不支持該請求'          break          default:          errMessage = `其他連接錯誤 --${code}`     }     return errMessage }

3、封裝request.ts

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

element-plus官網

安裝命令: npm install element-plus --save
  • 代碼如下:
import axios from 'axios'; import { errorCodeType } from '@/script/utils/error-code-type'; import { ElMessage, ElLoading } from 'element-plus';  // 創建axios實例 const service = axios.create({     // 服務接口請求     baseURL: import.meta.env.VITE_APP_BASE_API,     // 超時設置     // timeout: 15000,     headers:{'Content-Type':'application/json;charset=utf-8'} })  let loading:any; //正在請求的數量 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()     // 是否需要設置 token放在請求頭     // config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個請求攜帶自定義token 請根據實際情況自行修改     // get請求映射params參數     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) })  // 響應攔截器 service.interceptors.response.use((res:any) => {         hideLoading()         // 未設置狀態碼則默認成功狀態         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 = "系統接口請求超時";         }         else if (message.includes("Request failed with status code")) {             message = "系統接口" + message.substr(message.length - 3) + "異常";         }         ElMessage.error({             message: message,             duration: 5 * 1000         })         return Promise.reject(error)     } )  export default service;

4、自動導入vue3相關函數(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、自動導入Element Plus 相關函數(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...                 // 自動導入 Vue 相關函數,如:ref, reactive, toRef 等                 imports: ["vue"],                  // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)                 // 自動導入 Element Plus 相關函數,如:ElMessage, ElMessageBox... (帶樣式)                 resolvers: [                     ElementPlusResolver(),                      // Auto import icon components                     // 自動導入圖標組件                     IconsResolver({                         prefix: "Icon",                     }),                 ],                  dts: path.resolve(pathSrc, "auto-imports.d.ts"),             }),                          // 自動導入 Element Plus 組件             Components({                 resolvers: [                     // Auto register icon components                     // 自動注冊圖標組件                     IconsResolver({                         enabledCollections: ["ep"],                     }),                     // Auto register Element Plus components                                         ElementPlusResolver(),                 ],                  dts: path.resolve(pathSrc, "components.d.ts"),             }),             // 圖標             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,// 在開發服務器啟動時自動在瀏覽器中打開應用程序             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 // 屏蔽服務器報錯             }         },         resolve:{             alias:{                 '@': pathSrc,             }         },         css:{             // css預處理器             /*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封裝

完整的環境變量配置文件.env.production和.env.development

7.1、項目根目錄的development文件內容如下

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

7.2、項目根目錄下的production文件內容如下

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

8、在任何vue文件內使用接口:

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

  • page-params.ts

  • 代碼如下:

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

總結

本篇討論的主要內容是:

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

(學習視頻分享:web前端開發、編程基礎視頻)

贊(0)
分享到: 更多 (0)
?
網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
久久精品五月,日韩不卡视频在线观看,国产精品videossex久久发布 ,久久av综合
激情婷婷综合| 国产毛片一区| 福利一区视频| 欧美99久久| 亚洲人成在线影院| 91成人精品观看| 久久精品国产亚洲一区二区三区| 久久毛片亚洲| 9久re热视频在线精品| 日韩三级视频| 国产伦乱精品| 成人日韩在线观看| 五月天久久网站| 日韩1区2区3区| 捆绑调教日本一区二区三区| 婷婷激情图片久久| 欧美亚洲福利| 欧美成人基地 | 91精品成人| 日韩精品第一| 免费看av不卡| 日韩精品一级二级| 国产精品欧美一区二区三区不卡| 午夜av不卡| 亚洲人成网站在线在线观看| 电影91久久久| 日韩中文字幕一区二区三区| 另类综合日韩欧美亚洲| 久久国产精品99国产| 精品一区二区三区的国产在线观看| 国内亚洲精品| 国产精品日本一区二区不卡视频| 亚洲精品网址| 精品黄色一级片| 美女尤物久久精品| 成人国产精品一区二区网站| 中文字幕一区二区三区四区久久 | 日韩免费小视频| 欧美日韩亚洲一区在线观看| 在线日韩电影| 欧美精品91| 亚洲一区二区三区四区五区午夜 | 久久av网站| 日韩中文欧美在线| 九九色在线视频| 国产精一区二区| 亚洲欧美日韩国产| 日本韩国欧美超级黄在线观看| 国产精品一区二区美女视频免费看 | 国产精品久久久久蜜臀 | 久久久噜噜噜| 精品一区二区三区视频在线播放| 老牛国产精品一区的观看方式| 日韩在线精品| 国产精品巨作av| 中文字幕免费一区二区| 久久亚洲精品中文字幕蜜潮电影| 美女精品久久| 日韩1区2区3区| 视频精品一区二区| 精品1区2区3区4区| 亚洲天堂1区| 国产成人免费| 国产精品毛片aⅴ一区二区三区| 亚洲欧美在线综合| 黄色免费成人| 激情久久中文字幕| www.九色在线| 精品美女久久| 国产精品magnet| 石原莉奈在线亚洲二区| 欧美午夜不卡| 国产一区观看| www.com.cn成人| 久久99久久人婷婷精品综合| 日本h片久久| 伊人久久亚洲| 国产精品毛片一区二区三区| 久久久久中文| 亚洲精品在线影院| 欧美亚洲国产精品久久| 亚洲伊人精品酒店| 日韩a一区二区| 亚洲精品中文字幕99999| 亚洲欧美视频| 国产精品tv| 激情亚洲影院在线观看| 丝袜美腿一区二区三区| 精品一区二区三区的国产在线观看| 亚洲一区不卡| 91亚洲一区| 日本免费久久| 国产精品日韩精品在线播放| 亚洲激情中文| 国产a久久精品一区二区三区| 亚洲精一区二区三区| 成人黄色av| 鲁大师影院一区二区三区| 精品一区二区三区亚洲| 爽好久久久欧美精品| 精品国产欧美日韩一区二区三区| 亚洲一区欧美激情| 97se综合| 久久久国产精品网站| 日韩一区二区三区精品视频第3页 日韩一区二区三区免费视频 | 国产精品试看| 欧美一级鲁丝片| 乱人伦精品视频在线观看| 蜜桃av一区二区在线观看| 婷婷综合激情| 中文字幕在线高清| 欧美激情在线精品一区二区三区| 亚洲人成亚洲精品| 欧美手机在线| 久久69成人| 日韩精品一区第一页| 久久一区二区三区喷水| 久久中文字幕一区二区| 日本精品另类| 另类av一区二区| 免费精品国产| 日韩综合精品| 日韩激情av在线| 美女国产精品| 97人人精品| 欧美精品97| 欧美日韩亚洲一区三区| 中文不卡在线| 一区在线视频观看| 国产美女高潮在线| 国产精品66| 国产精品黄色片| 国产日韩欧美三级| 亚洲影视一区| 日韩精品欧美大片| 日韩高清电影一区| 欧美日韩调教| 国产欧美日韩一区二区三区四区| 国产无遮挡裸体免费久久| 亚洲资源网站| 日韩欧美中文字幕电影| 久久国产日韩欧美精品| 国产精品1区| 最新中文字幕在线播放| 久久天堂精品| 羞羞答答国产精品www一本| 亚洲人成精品久久久| 日韩中文字幕一区二区高清99| 日韩av电影一区| 你懂的国产精品| 午夜av一区| 亚洲人成精品久久久| 国产一区二区三区四区大秀| 午夜日本精品| 亚洲精品日本| 成年男女免费视频网站不卡| 免费人成在线不卡| 国语精品一区| 男女精品网站| 久久精品亚洲| 国产亚洲精品久久久久婷婷瑜伽| 久久国产三级精品| 欧美亚洲国产精品久久| 日本午夜精品久久久| 欧美男人天堂| 日韩高清在线不卡| 久久久久午夜电影| 69堂精品视频在线播放| 四虎影视精品| 亚洲人成网站在线在线观看| 日本黄色精品| 婷婷视频一区二区三区| 日韩成人亚洲| 国产伦精品一区二区三区视频 | 欧美成人综合| 国产精品日本一区二区不卡视频 | 亚洲另类黄色| 中文另类视频| 久久国产尿小便嘘嘘| 一本一道久久a久久精品蜜桃| 国产精品色在线网站| 9色国产精品| 国产成人黄色| 日本欧美韩国一区三区| 999精品色在线播放| 国产欧美二区| 男人的天堂久久精品| 欧美日韩免费观看视频| 国产亚洲精aa在线看| 亚洲在线观看| 中文在线免费视频| 日本aⅴ亚洲精品中文乱码| 视频一区中文| 动漫av一区| 久久精品99国产精品| 亚洲一区二区三区高清不卡| 日韩中文在线电影| 久久99青青| 日本va欧美va瓶| 激情五月色综合国产精品|