【VUE】如何有效管理重复请求

【VUE】如何管理重复请求

需求

重复的HTTP请求可能对应用程序性能造成很大影响,尤其是在用户快速点击或多次触发同一操作时。在Vue应用中,我们可以使用axios的请求拦截器(interceptors)配合AbortController来取消重复的HTTP请求

实现思路

通过使用axios的拦截器和AbortController API追踪并取消重复的HTTP请求,为每个请求生成唯一标识符,并在发现重复请求时使用AbortController的abort方法取消之前的请求,从而优化了网络性能并提升了用户体验。

代码实现

先创建一个文件来储存需要管理的API地址

requistDuplicateBlacklist.js

javascript 复制代码
export default [
    '/test/list&post',
    '/test/list&get',
    '/test/watch/.*&get'
]

使用&符号分割了请求地址与请求方式;当地址上有动态变化的部分时用.*代替,方便稍后的正则匹配;

然后我们封装一下axios

axios.js

javascript 复制代码
import axios from 'axios';
import requistDuplicateBlacklist from './requistDuplicateBlacklist'
//初始化window.cancelTokenSources变量
if(!window.cancelTokenSources){
  window.cancelTokenSources={}
}
// request拦截器
service.interceptors.request.use(
(config) => {
    let key = config.url+'&'+config.method;
    for(let item of requistDuplicateBlacklist){
      const regex = new RegExp('^' + item + '$');
      const isMatch = regex.test(key);
      if(isMatch){
        if(window.cancelTokenSources[key]){
          //如果之前有未完成请求,先中断
          window.cancelTokenSources[key].abort()
        }
        let controller = new AbortController();
        window.cancelTokenSources[key] = controller;//将要管理的请求储存在window.cancelTokenSources内
        config.signal = controller.signal
        break;
      }
    }
    ...
)
// 响应拦截器
service.interceptors.response.use(
(res) => {
let key = res.config.url+'&'+res.config.method;
    delete window.cancelTokenSources[key];//请求结束,从window.cancelTokenSources中删除
}
)

效果

如图,当存在重复请求时,上一个请求将会被取消,只保留最后一次请求。

相关推荐
KaMeidebaby3 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl4 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf4 小时前
Python 异常处理
前端·后端·python
sugar__salt4 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo4 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉4 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
小妖6665 小时前
js 生成随机数技巧 Math.random().toString(36)
javascript·随机数