实战教程vite+vue3.0+ts中如何封装axios?(vue怎么封装axios)

admin148856年前0条评论

对于于vue中应用axios的作为前端以及后端接口交互工具的用法文章,收集某博客上不可胜数。因为名目从0到1最先需要基于vite+vue3.0+ts中封装axios,以是今天让小编来给人人布置axios整合vite+vue3.0+ts的细致封装步调。记载一下自身封装步调,随着我的措施,撸起来。。。

一、布置axios

  1. npm i axios

细致:这里的布置命令便是默认布置最新版本的axios

二、封装申请同伴代码提醒error-code-type.ts

代码下列:

  1. export const errorCodeType = function(code:string):string{
  2.     let errMessage:string = "未知同伴"
  3.     switch (code) {
  4.         case 400: 
  5.         errMessage = '同伴的申请'
  6.         break
  7.         case 401: 
  8.         errMessage = '未授权,请从新登录'
  9.         break
  10.         case 403: 
  11.         errMessage = '推辞访问'
  12.         break
  13.         case 404: 
  14.         errMessage = '申请同伴,未找到该资本'
  15.         break
  16.         case 405: 
  17.         errMessage = '申请方法未许可'
  18.         break
  19.         case 408: 
  20.         errMessage = '申请超时'
  21.         break
  22.         case 500: 
  23.         errMessage = '效劳器端失足'
  24.         break
  25.         case 501: 
  26.         errMessage = '收集未实现'
  27.         break
  28.         case 502: 
  29.         errMessage = '收集同伴'
  30.         break
  31.         case 503: 
  32.         errMessage = '效劳不可用'
  33.         break
  34.         case 504: 
  35.         errMessage = '收集超时'
  36.         break
  37.         case 505: 
  38.         errMessage = 'http版本不反对于该申请'
  39.         break
  40.         default: 
  41.         errMessage = `其余连接同伴 --${code}`
  42.     }
  43.     return errMessage
  44. }

三、封装request.ts

这里用到的element-plus人人能够参考其官网布置就可,传递门:element-plus官网

布置命令:

  1. npm install element-plus --save

代码下列:

  1. import axios from 'axios';
  2. import { errorCodeType } from '@/script/utils/error-code-type';
  3. import { ElMessage, ElLoading } from 'element-plus';
  4.  
  5. // 建立axios实例
  6. const service = axios.create({
  7.     // 效劳接口申请
  8.     baseURL: import.meta.env.VITE_APP_BASE_API,
  9.     // 超时配置
  10.     // timeout: 15000,
  11.     headers:{'Content-Type':'application/json;charset=utf-8'}
  12. })
  13.  
  14. let loading:any;
  15. //正在申请的数目
  16. let requestCount:number = 0
  17. //显示loading
  18. const showLoading = () => {
  19.     if (requestCount === 0 && !loading) {
  20.         //加载中显示样式能够自行修改
  21.         loading = ElLoading.service({
  22.             text: "冒去世加载中,请稍后...",
  23.             background: 'rgba(0, 0, 0, 0.7)',
  24.             spinner: 'el-icon-loading',
  25.         })
  26.     }
  27.     requestCount++;
  28. }
  29. //隐蔽loading
  30. const hideLoading = () => {
  31.     requestCount--
  32.     if (requestCount == 0) {
  33.         loading.close()
  34.     }
  35. }
  36.  
  37. // 申请拦截
  38. service.interceptors.request.use(config => {
  39.     showLoading()
  40.     // 是否需要配置 token放在申请头
  41.     // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每一个申请照顾自界说token 请依据实践状况自行修改
  42.     // get申请照射params参数
  43.     if (config.method === 'get' && config.params) {
  44.         let url = config.url + '?';
  45.         for (const propName of Object.keys(config.params)) {
  46.             const value = config.params[propName];
  47.             var part = encodeURIComponent(propName) + "=";
  48.             if (value !== null && typeof(value) !== "undefined") {
  49.                  // 工具解决
  50.                 if (typeof value === 'object') {
  51.                     for (const key of Object.keys(value)) {
  52.                         let params = propName + '[' + key + ']';
  53.                         var subPart = encodeURIComponent(params) + "=";
  54.                         url += subPart + encodeURIComponent(value[key]) + "&";
  55.                     }
  56.                 } else {
  57.                     url += part + encodeURIComponent(value) + "&";
  58.                 }
  59.             }
  60.         }
  61.         url = url.slice(0, -1);
  62.         config.params = {};
  63.         config.url = url;
  64.     }
  65.     return config
  66. }, error => {
  67.     console.log(error)
  68.     Promise.reject(error)
  69. })
  70.  
  71. // 响应拦截器
  72. service.interceptors.response.use((res:any) => {
  73.         hideLoading()
  74.         // 未配置状态码则默认胜利状态
  75.         const code = res.data['code'] || 200;
  76.         // 获取同伴信息
  77.         const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default')
  78.         if(code === 200){
  79.             return Promise.resolve(res.data)
  80.         }else{
  81.             ElMessage.error(msg)
  82.             return Promise.reject(res.data)
  83.         }
  84.     },
  85.     error => {
  86.         console.log('err' + error)
  87.         hideLoading()
  88.         let { message } = error;
  89.         if (message == "Network Error") {
  90.             message = "后端接口连接异样";
  91.         }
  92.         else if (message.includes("timeout")) {
  93.             message = "系统接口申请超时";
  94.         }
  95.         else if (message.includes("Request failed with status code")) {
  96.             message = "系统接口" + message.substr(message.length - 3) + "异样";
  97.         }
  98.         ElMessage.error({
  99.             message: message,
  100.             duration: 5 * 1000
  101.         })
  102.         return Promise.reject(error)
  103.     }
  104. )
  105.  
  106. export default service;

四、主动导入vue3相干函数(auto-imports.d.ts)

auto-imports.d.ts放在src目录下

细致:需要布置yarn add unplugin-auto-import或者npm i unplugin-auto-import -D

布置完重启名目

代码下列:

  1. declare global {
  2.   const computed: typeof import('vue')['computed']
  3.   const createApp: typeof import('vue')['createApp']
  4.   const customRef: typeof import('vue')['customRef']
  5.   const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
  6.   const defineComponent: typeof import('vue')['defineComponent']
  7.   const effectScope: typeof import('vue')['effectScope']
  8.   const EffectScope: typeof import('vue')['EffectScope']
  9.   const getCurrentInstance: typeof import('vue')['getCurrentInstance']
  10.   const getCurrentScope: typeof import('vue')['getCurrentScope']
  11.   const h: typeof import('vue')['h']
  12.   const inject: typeof import('vue')['inject']
  13.   const isReadonly: typeof import('vue')['isReadonly']
  14.   const isRef: typeof import('vue')['isRef']
  15.   const markRaw: typeof import('vue')['markRaw']
  16.   const nextTick: typeof import('vue')['nextTick']
  17.   const onActivated: typeof import('vue')['onActivated']
  18.   const onBeforeMount: typeof import('vue')['onBeforeMount']
  19.   const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
  20.   const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
  21.   const onDeactivated: typeof import('vue')['onDeactivated']
  22.   const onErrorCaptured: typeof import('vue')['onErrorCaptured']
  23.   const onMounted: typeof import('vue')['onMounted']
  24.   const onRenderTracked: typeof import('vue')['onRenderTracked']
  25.   const onRenderTriggered: typeof import('vue')['onRenderTriggered']
  26.   const onScopeDispose: typeof import('vue')['onScopeDispose']
  27.   const onServerPrefetch: typeof import('vue')['onServerPrefetch']
  28.   const onUnmounted: typeof import('vue')['onUnmounted']
  29.   const onUpdated: typeof import('vue')['onUpdated']
  30.   const provide: typeof import('vue')['provide']
  31.   const reactive: typeof import('vue')['reactive']
  32.   const readonly: typeof import('vue')['readonly']
  33.   const ref: typeof import('vue')['ref']
  34.   const resolveComponent: typeof import('vue')['resolveComponent']
  35.   const shallowReactive: typeof import('vue')['shallowReactive']
  36.   const shallowReadonly: typeof import('vue')['shallowReadonly']
  37.   const shallowRef: typeof import('vue')['shallowRef']
  38.   const toRaw: typeof import('vue')['toRaw']
  39.   const toRef: typeof import('vue')['toRef']
  40.   const toRefs: typeof import('vue')['toRefs']
  41.   const triggerRef: typeof import('vue')['triggerRef']
  42.   const unref: typeof import('vue')['unref']
  43.   const useAttrs: typeof import('vue')['useAttrs']
  44.   const useCssModule: typeof import('vue')['useCssModule']
  45.   const useCssVars: typeof import('vue')['useCssVars']
  46.   const useSlots: typeof import('vue')['useSlots']
  47.   const watch: typeof import('vue')['watch']
  48.   const watchEffect: typeof import('vue')['watchEffect']
  49. }
  50. export {}

五、主动导入ElementPlus相干函数(components.d.ts)

细致:需要布置npm i unplugin-vue-components -D或者yarn add unplugin-vue-components

布置完重启名目

  1. import '@vue/runtime-core'
  2.  
  3. declare module '@vue/runtime-core' {
  4.   export interface GlobalComponents {
  5.     ElCard: typeof import('element-plus/es')['ElCard']
  6.     ElCol: typeof import('element-plus/es')['ElCol']
  7.     ElContainer: typeof import('element-plus/es')['ElContainer']
  8.     ElFooter: typeof import('element-plus/es')['ElFooter']
  9.     ElHeader: typeof import('element-plus/es')['ElHeader']
  10.     ElMain: typeof import('element-plus/es')['ElMain']
  11.     ElOption: typeof import('element-plus/es')['ElOption']
  12.     ElPagination: typeof import('element-plus/es')['ElPagination']
  13.     ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
  14.     ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
  15.     ElRow: typeof import('element-plus/es')['ElRow']
  16.     ElSelect: typeof import('element-plus/es')['ElSelect']
  17.     ElTable: typeof import('element-plus/es')['ElTable']
  18.     ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
  19.     Loading: typeof import('element-plus/es')['ElLoadingDirective']
  20.   }
  21. }
  22.  
  23. export {}

六、vite.config.ts文件配置

细致:需要布置npm i unplugin-icons或者yarn add unplugin-icons

  1. import { defineConfig } from 'vite';
  2. import vue from '@vitejs/plugin-vue';
  3. import Icons from "unplugin-icons/vite";
  4. import IconsResolver from "unplugin-icons/resolver";
  5. import AutoImport from "unplugin-auto-import/vite";
  6. import Components from "unplugin-vue-components/vite";
  7. import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
  8. import { loadEnv } from 'vite';
  9. import path from 'path';
  10. // 门路
  11. const pathSrc = path.resolve(__dirname,'src')
  12.  
  13. // https://vitejs.dev/config/
  14. export default({ co妹妹and, mode }) => {
  15.     return defineConfig({
  16.         plugins: [
  17.             vue(),
  18.             AutoImport({
  19.                 // Auto import functions from Vue, e.g. ref, reactive, toRef...
  20.                 // 主动导入 Vue 相干函数,如:ref, reactive, toRef 等
  21.                 imports: ["vue"],
  22.  
  23.                 // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
  24.                 // 主动导入 Element Plus 相干函数,如:ElMessage, ElMessageBox... (带样式)
  25.                 resolvers: [
  26.                     ElementPlusResolver(),
  27.  
  28.                     // Auto import icon components
  29.                     // 主动导入图标组件
  30.                     IconsResolver({
  31.                         prefix: "Icon",
  32.                     }),
  33.                 ],
  34.  
  35.                 dts: path.resolve(pathSrc, "auto-imports.d.ts"),
  36.             }),
  37.              
  38.             // 主动导入 Element Plus 组件
  39.             Components({
  40.                 resolvers: [
  41.                     // Auto register icon components
  42.                     // 主动注册图标组件
  43.                     IconsResolver({
  44.                         enabledCollections: ["ep"],
  45.                     }),
  46.                     // Auto register Element Plus components
  47.                     
  48.                     ElementPlusResolver(),
  49.                 ],
  50.  
  51.                 dts: path.resolve(pathSrc, "components.d.ts"),
  52.             }),
  53.             // 图标
  54.             Icons({
  55.                 autoInstall: true,
  56.             }),
  57.         ],
  58.         server:{
  59.             host: '127.0.0.1',
  60.             //port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),
  61.             port: 3000,
  62.             strictPort: true, // 端口被占用间接退出
  63.             https: false,
  64.             open: true,// 在开辟效劳器启动时主动在浏览器中关上应用程序
  65.             proxy: {
  66.                 // 字符串简写写法
  67.                 '^/api': {
  68.                     target: mode==='development'?loadEnv(mode, process.cwd()).VITE_APP_DEV_URL:loadEnv(mode, process.cwd()).VITE_APP_PROD_URL,
  69.                     changeOrigin: true,
  70.                     rewrite: (path) => path.replace(/^\/api/, '')
  71.                 }
  72.             },
  73.             hmr:{
  74.                 overlay: false // 屏障效劳器报错
  75.             }
  76.         },
  77.         resolve:{
  78.             alias:{
  79.                 '@': pathSrc,
  80.             }
  81.         },
  82.         css:{
  83.             // css预解决器
  84.             /*preprocessorOptions: {
  85.                 scss: {
  86.                     additionalData: '@import "@/assets/styles/global.scss";'
  87.                 }
  88.             }*/
  89.              preprocessorOptions: {
  90.                less: {
  91.                  charset: false,
  92.                  additionalData: '@import "./src/assets/style/global.less";',
  93.                 },
  94.             },
  95.         },
  96.         build:{
  97.             chunkSizeWarningLimit: 1500, // 分块打包,剖析块,将年夜块剖析成更小的块
  98.             rollupOptions: {
  99.                 output:{
  100.                     manualChunks(id) {
  101.                         if (id.includes('node_modules')) {
  102.                             return id.toString().split('node_modules/')[1].split('/')[0].toString();
  103.                         }
  104.                     }
  105.                 }
  106.             }
  107.         }
  108.     })
  109. }

七、应用axios封装

完好的情况变量配置文件.env.production以及.env.development

7.一、名目根目录的development文件内容下列

  1. # 开辟情况
  2. VITE_APP_TITLE = "阿绵"
  3. # 端口号 
  4. VITE_APP_PORT = "3000"
  5. # 申请接口 
  6. VITE_APP_DEV_URL = "http://localhost:8088"
  7. # 前缀 
  8. VITE_APP_BASE_API = "/api"

7.二、名目根目录下的production文件内容下列

  1. # 开辟情况 
  2. VITE_APP_TITLE = "阿绵"
  3. # 端口号 
  4. VITE_APP_PORT = "3000"
  5. # 申请接口 
  6. VITE_APP_DEV_URL = "http://localhost:8088"
  7. # 前缀 
  8. VITE_APP_BASE_API = "/api"

八、在任何vue文件内应用接口:

细致:这里另有一个PageParams全局分页工具:

page-params.ts

代码下列:

  1. // 全局对于抗分页参数范例申明 
  2. declare interface PageParams {
  3.     pageNum: number, pageSize: number, type?: Model, // 可选参数 
  4.     readonly sort?: string // 只读可选参数 
  5. } interface Model { type?: string }
  6. export default PageParams;
你可能想看:

本文链接:https://addon.ciliseo.com/shi-zhan-jiao-cheng-vitevue30ts-zhong-ru-he-feng-zhuang-axios.html

axios实战教程vitets接口错误注意项目函数参数代码文件放在图标如何vue
教程教程是什么意思教程视频教程的英文教程网教程魔方教程手工教程之家网教程画画教程之家教程之家官网教程今日己更新2023教程网站教程自学网教程英语教程资源网教程学习之家教程英文教程是什么教程学分班教程支语教程是什么dcard文件文件管理文件扫描成电子版文件传输助手文件管理安装文件传输助手下载文件夹怎么弄文件传输文件怎么转换成pdf格式文件夹在哪里找文件传输助手网页版文件夹怎么设置密码文件传输助手网页版微信文件夹文件压缩文件压缩免费软件文件格式转换器文件夹怎么加密码不让别人打开文件翻译文件在线对比文件夹英文文件袋文件蜈蚣文件恢复代码代码生成器代码ai编写代码编程教学入门代码网站代码怎么编写代码编程软件代码编辑器代码怎么运行代码随想录代码大全代码在线运行代码练习代码怎么写代码大全可复制代码运行在线工具代码对比代码随想录github代码ai代码高亮代码随想录完整版pdf代码查重实战十一人实战教学漫画阅读免费阅读实战演练实战篮球鞋实战和手艺有什么区别实战化训练实战化程度再高的对抗和真正的实战实战实训实战英语实战经验实战宝典实战失效实战技巧实战伤寒论六个方子实战化实战麻将王实战练兵实战导向实战乒乓剪辑实战英文实战最强武术实战球衣实战台股可转债实战达人实战台股可转债pdf实战的知识实战达人诈骗接口类型接口仅支持数字音频设备接口typec接口是什么意思
教程之家官网文件管理文件管理安装文件夹怎么设置密码文件在线对比文件蜈蚣代码代码编辑器代码练习实战十一人实战教学漫画阅读免费阅读实战演练实战和手艺有什么区别实战英语实战经验实战失效实战伤寒论六个方子实战化实战麻将王实战练兵实战导向实战乒乓剪辑实战英文实战最强武术实战台股可转债实战达人诈骗接口仅支持数字音频设备接口typec接口和抽象类的区别接口报文接口板接口英文接口测试接口自动化接口文档示例注意力缺陷障碍症最佳治愈方法注意力不集中容易走神是什么原因注意缺陷多动障碍是什么意思注意力不集中怎么改善注意力缺陷症注意力缺陷多动障碍的表现注意力不集中注意危险标志注意高温警示标识注意安全注意标识图片注意安全标识牌注意安全警示牌图片注意力缺陷障碍注意事项英文注意英文注意安全英文注意力注意事项项目计划书项目设计课题研究高中综合评价项目网项目管理的主要内容包括哪些项目的英文项目管理证书报考条件要求项目设计报告怎么写项目经理岗位职责及工作内容项目设计高中综评项目从立项到结束的流程图项目建议书项目活动设计综评填写项目管理过程五个阶段流程图项目经理岗位职责项目设计高中综评典例项目英文项目符号项目负责人英文项目进度表项目式学习

网友评论

扫一扫二维码添加客服微信

关于我们建站招商建站服务