欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > vue 请求竞态 中断请求 解决切换表格数据,数据发生错乱

vue 请求竞态 中断请求 解决切换表格数据,数据发生错乱

2024/10/24 19:21:00 来源:https://blog.csdn.net/Vue1024/article/details/142868451  浏览:    关键词:vue 请求竞态 中断请求 解决切换表格数据,数据发生错乱

//1,声明缓存请求的集合
const pendingRequest = new Map();
//2,请求url和method生成key
const generateRequestKey = <T extends AxiosRequestConfig>(config: T) => {const { method, url } = configreturn [method, url].join("&")
}
//3,缓存正在pending状态的请求
const addPendingRequest = (config: AxiosRequestConfig) => {const requestKey = generateRequestKey(config)// 判断是否正在pending中if (pendingRequest.has(requestKey)) {const controller = pendingRequest.get(requestKey)//终止请求controller.abort()pendingRequest.delete(requestKey)}// 添加请求const controller = new AbortController()config.signal = controller.signalpendingRequest.set(requestKey, controller)
}
// 4,删除缓存的请求
const removePendingRequest = (config: AxiosRequestConfig) => {const requestKey = generateRequestKey(config)if (pendingRequest.has(requestKey)) {pendingRequest.delete(requestKey)}
}

在请求拦截器里添加

// 添加请求拦截器
service.interceptors.request.use((config) => {addPendingRequest(config)// 在发送请求之前做些什么return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});

在响应拦截器里移除

// 添加响应拦截器
service.interceptors.response.use((response: any) => {removePendingRequest(response.config)
})

版权声明:

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

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