• axios 实现请求 loading 效果


    在这里插入图片描述

    前景提要:
    ts 简易封装 axios,统一 API
    实现在 config 中配置开关拦截器

    loading 分为全屏 loading 和局部 loading。
    axios 中设置 loading 只能设置全屏 loading,因为局部 loading 需要当前局部的 dom,在 axios 中显然拿不到发起请求的元素 dom。

    封装 loading 拦截器

    1. 请求拦截器开启 loading
    2. 响应拦截器关闭 loading
      • 注意:无论请求成功或失败都应关闭 loading,因此在响应拦截器两个回调中都要关闭 loading。
    import { AxiosError, AxiosResponse } from "axios";
    import { ElLoading } from "element-plus";
    import { MyInternalAxiosRequestConfig } from "./request";
    
    /**
     * el-loading 有两种方式调用:指令和服务。
     * 指令可以绑定到元素上,局部loading
     * 此处以服务方式调用loading,并且根据请求配置 showLoading 来决定请求是否开启loading
     * 此loading在全局拦截器生效,服务方式默认就是全屏
     */
    
    /* 全局请求 loading(服务方式调用) */
    let loadingInstance: ReturnType<typeof ElLoading.service>;
    
    const startElementLoading = () => {
        loadingInstance = ElLoading.service({
            fullscreen: true,
            lock: true,
            text: "Loading",
            background: "rgba(0, 0, 0, 0.7)"
            // spinner:	自定义加载图标类名
            // customClass:	Loading 的自定义类名
        });
    };
    
    const endElementLoading = (loadingInstance: ReturnType<typeof ElLoading.service>) => loadingInstance.close();
    
    /**
     * 开启loading
     * @param {import("..").AxiosRequestConfig} config
     * @returns
     */
    export function showLoading(config: MyInternalAxiosRequestConfig) {
        if (config.showLoading === false) return config;
        startElementLoading();
        return config;
    }
    
    /**
     * 请求成功关闭 loading
     * @param {import("axios").AxiosResponse} res
     * @returns
     */
    export function closeLoadingOnFulfilled(res: AxiosResponse) {
        if (loadingInstance) endElementLoading(loadingInstance);
        return res;
    }
    
    /**
     * 请求失败关闭 loading
     * @param {import("axios").AxiosError} err
     * @returns
     */
    export function closeLoadingOnRejected(err: AxiosError) {
        if (loadingInstance) endElementLoading(loadingInstance);
        throw err;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    在 config 中配置 loading 开关

    const DEFAULT_EXTRA_FEATURE_CONFIG = { showLoading: true, showMessage: true, retry: true };
    
    /** 扩展 axios 的请求配置类型 */
    export interface MyAxiosRequestConfig<TReqBodyData = any> extends AxiosRequestConfig<TReqBodyData> {
        showLoading?: boolean;
        showMessage?: boolean;
        retry?: boolean;
    }
    
    /** 给拦截器使用 */
    export interface MyInternalAxiosRequestConfig extends InternalAxiosRequestConfig {
        showLoading?: boolean;
        showMessage?: boolean;
        retry?: boolean;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    axios 实例化后注册 loading 拦截器

    import HttpRequest from "./http/request";
    import { compareUrl, filterFulfilledUrlOnFulfilled, filterFulfilledUrlOnRejected } from "./http/debounceReq";
    import { closeLoadingOnFulfilled, closeLoadingOnRejected, showLoading } from "./http/loading";
    import { responseMessageOnFulfilled } from "./http/message";
    import { getTokenResponseInterceptor, setAccessTokenRequestInterceptor } from "./http/token";
    import { retryRequest } from "./http/retryRequest";
    
    const httpRequest = new HttpRequest({
        baseURL: import.meta.env.VITE_APP_API_BASE_URL,
        timeout: import.meta.env.VITE_APP_API_TIMEOUT
    });
    
    // loading
    httpRequest.getInstance().interceptors.request.use(showLoading);
    httpRequest.getInstance().interceptors.response.use(closeLoadingOnFulfilled, closeLoadingOnRejected);
    
    export default httpRequest;
    ```
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    计算机毕业设计ssm+vue基本微信小程序的考试刷题及分析系统小程序
    【Midjourney入门教程4】与AI对话,写好prompt的必会方法
    RK3399- hdmi-in (tc35874)添加插拔状态读取
    202212 青少年等级考试机器人实操真题三级
    【技巧】Word和Excel如何互相转换?
    【Linux集群教程】12 集群安全防御 - 安全防御概述和Linux防火墙
    根据Java8 流 根据多个字段对 list 进行去重
    C++&qt day8
    一个讲座监控软件
    性能调优读书笔记(下篇)
  • 原文地址:https://blog.csdn.net/qq_43220213/article/details/134194610