欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Vue3 axios 请求设置 signal 信号属性,以便 abort 取消请求

Vue3 axios 请求设置 signal 信号属性,以便 abort 取消请求

2025/6/20 15:23:45 来源:https://blog.csdn.net/BillKu/article/details/148668472  浏览:    关键词:Vue3 axios 请求设置 signal 信号属性,以便 abort 取消请求

 api:

taskMessage.ts

// 通过用户名(账号),查询任务列表
export const taskService = (signal?: AbortSignal) => {return request.get("/task", {// 设置 signal 信号属性,后续就可以通过 abort 取消请求signal: signal});
};// 通过用户名(账号),查询消息列表
export const messageService = (signal?: AbortSignal) => {return request.get("/message", {// 设置 signal 信号属性,后续就可以通过 abort 取消请求signal: signal});
};

发送 / 取消请求:

useFetchService.ts

import { onUnmounted, ref, type Ref } from "vue";
import type { AxiosResponse } from "axios";interface IFetchResponse<T> {data: Ref<T[]>;error: Ref<string>;isLoading: Ref<boolean>;refetch: () => Promise<void>;
}/*** 请求服务 hook* @param service 请求服务方法* @param args 请求参数* @returns*/
export const useFetchService = async <T>(service: (...args: any[]) => Promise<AxiosResponse<any, any>>,args: any[] = []
) => {// 请求服务const fetchService = async () => {try {state.isLoading.value = true;state.data.value = [];state.error.value = "";// 在参数数组中增加设置信号 AbortSignal,关联请求,以便能取消请求args.push(controller.signal);const result = await service(...args);state.data.value = result.data;} catch (error) {state.error.value = `服务调用失败: ${service.name}` + error;console.error(state.error.value);} finally {state.isLoading.value = false;}};// 创建及初始化状态const state: IFetchResponse<T> = {data: ref([]),error: ref(""),isLoading: ref(false),refetch: fetchService};// 创建 AbortController 用于取消请求const controller = new AbortController();onUnmounted(() => {// 取消请求controller.abort();});// 执行请求服务await fetchService();// 返回状态return state;
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词