所有分类
  • 所有分类
  • 织梦模板

实战教程vite+vue3.0+ts中如何封装axios?

关于vue中使用axios的作为前端和后端接口交互工具的用法文章,网络某博客上数不胜数。因为项目从0到1开始需要基于vite+vue3.0+ts中封装axios,所以今天让小编来给大家安排axios整合vite+vue3.0+ts的具体封装步骤。记录一下自己封装步骤,跟着我的步伐,撸起来。。。

1、安装axios

  1. npm i axios

注意:这里的安装命令就是默认安装最新版本的axios

2、封装请求错误代码提示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. }

3、封装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;

4、自动导入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 {}

5、自动导入Element Plus 相关函数(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 {}

6、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({ command, 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. }

7、使用axios封装

完整的环境变量配置文件.env.production.env.development

7.1、项目根目录的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.2、项目根目录下的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"

8、在任何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;
常见问题
所有VIP可以商用吗,会不会有版权问题?
本站提供的源码大部分可以作为源码开发参考和学习,部分开源可商用。
账号可以分享给其他人使用吗?
您好,账号禁止共享,我们有验证机制的,会自动封号处理,谢谢配合。
如果遇到问题怎么联系解决呢?
最快的途径是在导航菜单选择提交【售后】会在24小时处理
下载的源码可以使用吗?
我们会在显著的地方表明【已测试】,显示已测试的都是小编测试过 。
1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
5.如有侵权请联系客服邮件770973008@qq.com
原文链接:https://www.56admin.com/26647.html,转载请注明出处。
0
分享海报

评论0

请先
九年老站,质量有保证,90%亲自测试!优惠原价199模板币终生SVIP,优惠价68模板币! 数量有限! 购买SVIP 所有资源免积分下载,畅享无忧!
显示验证码
没有账号?注册  忘记密码?