昌都市网站建设_网站建设公司_前端工程师_seo优化
2025/12/18 14:37:03 网站建设 项目流程

为了避免在循环中重复调用同一接口,可以引入状态管理机制:当针对特定ID的接口调用启动时,将其标记为"进行中"状态,阻止后续重复请求。待接口返回数据后,再更新存储状态并清除标记。

这段代码的核心是避免重复请求图表接口,通过「缓存(chartConfigCache)+待处理列表(pendingCharts)」双重校验,保证同一个图表 ID 只会被请求一次,提升页面性能、减少接口压力。

const chartConfigCache = new Map(); const pendingCharts = ref([]); // 在循环外面定义 // ========== 步骤1:准备基础数据 ========== // 1. 从外层数据中提取图表唯一ID(核心标识) const chartId = outerJson?.id; // 2. 检查该图表是否已经在pendingCharts列表中(是否正在/已经处理) const chartExistsInPending = pendingCharts.value.some(chart => chart.id === chartId);
// ========== 步骤2:优先校验缓存(最高优先级) ========== // 从缓存Map中获取该图表的历史数据 const cachedData = chartConfigCache.get(chartId); if (cachedData) { // 缓存命中:直接把缓存数据存入pendingCharts(供页面渲染) pendingCharts.value.push({ id: chartId, content: cachedData.content, // 缓存的图表内容 height: cachedData.height, // 缓存的图表高度 timestamp: Date.now() // 记录最新时间戳 }); continue; // 跳过后续所有逻辑(包括接口请求) }
// ========== 步骤3:校验待处理列表(次优先级) ========== if (chartExistsInPending) { // 该图表已在处理中/已处理,直接跳过,避免重复请求 continue; }
// ========== 步骤4:无缓存+未处理 → 发起接口请求 ========== // 第一步:先标记为“处理中”(存入空数据),防止并发请求 pendingCharts.value.push({ id: chartId, content: null, // null表示正在处理,未拿到数据 height: null, timestamp: Date.now() }); // 第二步:调用接口获取图表真实数据 const res = await getEchartsData(outerJson.id); if (res.code == 200) { // 接口请求成功 if(res.result && res.result.output){ // 数据格式合法 // 找到pendingCharts中该图表的位置,替换为空数据为真实数据 const chartIndex = pendingCharts.value.findIndex(chart => chart.id === chartId); if (chartIndex !== -1) { pendingCharts.value[chartIndex] = { id: chartId, content: res.result.output, // 接口返回的图表内容 height: res.result.height, // 接口返回的图表高度 timestamp: Date.now() }; } // 【补充】原代码漏了这一步:接口返回后应该存入缓存,下次直接用 chartConfigCache.set(chartId, { content: res.result.output, height: res.result.height, url: res.result.url // 如果有url的话 }); } }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询