08-Vue3 axios对象封装

本文详细介绍了如何在Vue3和TypeScript环境中搭建Vite2脚手架,包括环境配置、路由、状态管理、axios封装以及使用Element-Plus框架。重点讲述了axios的封装,实现了请求配置、拦截器、中止请求等功能,并通过实例展示了其在项目中的应用。同时,提供了完整的代码示例和实际运行效果。
摘要由CSDN通过智能技术生成

Vite2+Vue3+TypeScript+Element-plus脚手架搭建系列

✅01-初始化 Vite 项目
✅02-配置 Vite2 环境变量
✅03-Vite2 配置及说明
✅04-Vue3 使用 SCSS
✅05-Vue3 路由配置
✅06-TypeScript 配置及说明
✅07-Vue3 使用 axios
✅08-Vue3 axios 对象封装
✅09-ESLint 配置及说明
✅10-ESLint 与 Prettier 集成配置及说明
✅11-Mock.js 模拟接口数据
✅12-Vite2 引入 Element-Plus 框架
✅13-渐变+透明样式实现清爽登录页
✅14-Element-Plus 实现后台管理系统布局
✅15-Pinia 实现 store 状态管理
✅16-Vue3 动态路由权限控制


源码地址:GitHub / 码云


Vue3 axios对象封装

🎯 目标

封装axios相关工具类,实现功能包含axios配置、拦截器、发送请求、中止请求。

🍸 准备

调整文件&目录

/src/utils 目录下创建 axios 封装类。

utils文件目录结构如下:

📁 src

----📁 utils

--------📁 http

------------📄 abort-request.ts

------------📄 custom-axios.ts

------------📄 index.ts

------------📄 types.ts

🌈 Coding

定义类型

types.ts 代码如下:

import { AxiosRequestConfig, AxiosResponse } from "axios";

export interface InterceptorConfig<T> {
  // ↓是否开启中止请求功能
  enableAbortRequest?: boolean,
  // ↓请求拦截器
  interceptorRequest?: (value: AxiosRequestConfig) => AxiosRequestConfig | Promise<AxiosRequestConfig>
  // ↓请求拦截器异常处理
  interceptorRequestRejected?: (error: any) => any
  // ↓响应拦截器
  interceptorResponse?: ((value: AxiosResponse<T>) => AxiosResponse<any> | Promise<AxiosResponse<T>>)
  // ↓响应拦截器异常处理
  interceptorResponseRejected?: (error: any) => any
}

// ↓自定义请求配置
export interface CustomRequest<T> {
  // ↓原生axios配置
  customConfig?: AxiosRequestConfig;
  // ↓拦截器配置
  interceptorConfig: InterceptorConfig<T>
}

// ↓自定义响应内容
export interface CustomResponse {
  // ↓消息
  message: string;
  // ↓状态码
  code: number;
  // ↓数据集
  result: any
}

中止请求类

abort-request.ts 结构 如下(代码不全,文章顶部有源码地址):

// ↓中止axios请求类
export class AbortRequest {
  // ↓执行中的请求map集合。key=请求识别号,value=请求取消器
  private pendingMap = new Map<string, Canceler>()

  // ↓生成请求key
  genPendingKey(config: AxiosRequestConfig): string

  // ↓添加执行中请求
  addPending(config: AxiosRequestConfig) 

  // ↓移除执行中请求
  removePending(pendingKey: string) 

  // ↓清空执行中请求
  clearPending()

  // ↓中止执行中请求
  abort(pendingKey: string): boolean 
}

自定义 axios 类

custom-axios.ts 结构 如下(代码不全,文章顶部有源码地址):

// ↓自定义axios类
export class CustomAxios<T> {
  // ↓原生axios对象
  private instance: AxiosInstance
  // ↓axios请求中止对象
  private abortRequest: AbortRequest

  // ↓构造函数
  constructor(customRequest: CustomRequest<T>)

  // ↓使用拦截器
  useInterceptors(config: InterceptorConfig<T>)

  // ↓request请求
  request(config: AxiosRequestConfig): Promise<AxiosResponse<T>>

  // ↓get请求
  get(url: string, params?: object, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> 

  // ↓post请求
  post(url: string, data?: object, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>

  // ↓put请求
  put(url: string, data?: object, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>

  // ↓delete请求
  delete(url: string, data?: object, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>
}

实例化自定义 axios 对象

上面已经将工具类代码封装好,现在我们需要实例化一个对象,并对外暴露使用。index.ts 代码如下:

import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { CustomAxios } from './custom-axios';
import { CustomResponse } from './types';

// ↓实例化自定义axios
const customAxios = new CustomAxios<CustomResponse>({
  // ↓axios原生配置
  customConfig: {
    // ↓从环境变量读取VITE_BASE_URL
    baseURL: import.meta.env.VITE_BASE_URL as string,
    // ↓超时时间(10s)
    timeout: 10 * 1000,
    // ↓超时提示信息
    timeoutErrorMessage: '请求超时,请稍后再试。'
  },
  // ↓拦截器配置
  interceptorConfig: {
    // ↓开启中止请求功能
    enableAbortRequest: true,
    interceptorRequest: (config: AxiosRequestConfig) => {
      // TODO 请求拦截业务逻辑
      console.log('执行请求拦截器...');
      return config
    },
    interceptorResponse: (res: AxiosResponse) => {
      // TODO 相应拦截业务逻辑
      console.log('执行响应拦截器...');
      return res
    }
  }
});

export default customAxios;

Demo 组件

最后让 Demo 组件 Axios.vue 来调用和验证,代码如下:

<template>
  <!--HTTP请求demo -->
  <div>
    <h2>HTTP请求</h2>
    <button @click="httpGet">get请求</button>
    <button @click="httpPost">post请求</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import http from "@/utils/http/index";

export default defineComponent({
  name: "Axios",
  setup() {
    // ↓发送get请求
    const httpGet = () => {
      http
        .get("https://jsonplaceholder.typicode.com/posts/1")
        .then((response: any) => {
          console.log(response);
        });
    };
    // ↓发送post请求,快速双击可测试重复请求
    const httpPost = () => {
      http
        .post("https://jsonplaceholder.typicode.com/posts", {
          keyword: "code",
        })
        .then((response: any) => {
          console.log(response);
        });
    };

    return {
      httpGet,
      httpPost,
    };
  },
});
</script>

🎭 结果

  • 页面效果
    在这里插入图片描述
  • 点击按钮发送get和post请求,控制台输出如下日志:
    在这里插入图片描述
  • 快速点击两次“post请求”按钮,会弹出“重复请求被取消”的提示框,( 确保 src/utils/http/index.ts 中 enableAbortReques 配置为 true ),控制台输出如下日志:
    在这里插入图片描述
  • 配置 enableAbortRequest:false 关闭中止请求功能,快速点击两次“post请求”按钮,控制台输出如下日志:
    在这里插入图片描述

本文为博主原创文章,任何个人、团体、机构转载和摘录,请注明出处。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code-bee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值