MST

星途 面试题库

面试题:Vue基于Composition API封装网络请求函数的优化

假设已有一个基于Composition API封装的网络请求函数用于基本的GET、POST请求。现在要求对其进行优化,增加请求缓存功能,即相同的请求在一定时间内再次发起时,直接返回缓存中的数据,而不是重新请求。请描述实现思路并给出关键代码。
45.6万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建缓存对象:用于存储请求的缓存数据。
  2. 记录缓存时间:为每个缓存数据记录缓存时间,以便判断缓存是否过期。
  3. 封装请求函数:在原有网络请求函数基础上,每次请求前先检查缓存中是否有对应数据且未过期,若有则直接返回缓存数据,否则发起新请求并更新缓存。

关键代码

// 假设已有网络请求函数,例如:
const httpRequest = async (url, method = 'GET', data = null) => {
  // 实际的网络请求逻辑
  const response = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body: data ? JSON.stringify(data) : null
  });
  return response.json();
};

// 创建缓存对象
const requestCache = {};

// 封装带有缓存功能的请求函数
const cachedHttpRequest = async (url, method = 'GET', data = null, cacheTime = 5 * 1000) => {
  const cacheKey = `${url}-${method}-${JSON.stringify(data)}`;
  const cached = requestCache[cacheKey];
  if (cached && Date.now() - cached.timestamp < cacheTime) {
    return cached.data;
  }
  const response = await httpRequest(url, method, data);
  requestCache[cacheKey] = {
    data: response,
    timestamp: Date.now()
  };
  return response;
};