MST

星途 面试题库

面试题:Vue项目中如何优化网络请求缓存机制以处理动态参数情况

在Vue项目里,使用Vuex结合axios来管理网络请求缓存。现在有一个搜索接口 `/api/search`,它接受不同的关键词作为参数,例如 `/api/search?keyword=apple`。要求设计并实现一个缓存机制,既能缓存不同关键词搜索的结果,又能在缓存过期或者数据变化时更新缓存,同时要考虑性能和内存占用问题,请详细描述思路并给出关键代码。
30.0万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

思路

  1. 定义缓存结构:使用一个对象来存储不同关键词对应的搜索结果及缓存时间。
  2. 设置缓存过期时间:为每个缓存数据记录缓存时间,在每次获取缓存数据时检查是否过期。
  3. 利用Vuex管理缓存:将缓存数据存储在Vuex的state中,通过mutations和actions来操作缓存。
  4. 结合axios发送请求:在actions中使用axios发送搜索请求,请求前先检查缓存,若缓存未过期则直接返回缓存数据,否则发送请求并更新缓存。

关键代码

  1. Vuex模块
// store/modules/search.js
import axios from 'axios';

const state = {
  searchCache: {}
};

const mutations = {
  SET_SEARCH_CACHE(state, { keyword, result, timestamp }) {
    state.searchCache[keyword] = { result, timestamp };
  }
};

const actions = {
  async search({ state, commit }, keyword) {
    const cached = state.searchCache[keyword];
    const cacheDuration = 60 * 1000; // 缓存过期时间为1分钟
    if (cached && Date.now() - cached.timestamp < cacheDuration) {
      return cached.result;
    }
    try {
      const response = await axios.get(`/api/search?keyword=${keyword}`);
      commit('SET_SEARCH_CACHE', { keyword, result: response.data, timestamp: Date.now() });
      return response.data;
    } catch (error) {
      console.error('搜索请求失败', error);
      throw error;
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
  1. 在Vue组件中使用
<template>
  <div>
    <input v-model="keyword" placeholder="输入关键词">
    <button @click="search">搜索</button>
    <div v-if="searchResult">
      <pre>{{ searchResult }}</pre>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  data() {
    return {
      keyword: ''
    };
  },
  computed: {
    ...mapActions('search', ['search'])
  },
  methods: {
    async search() {
      try {
        this.searchResult = await this.search(this.keyword);
      } catch (error) {
        console.error('搜索失败', error);
      }
    }
  }
};
</script>

性能和内存占用优化

  1. 设置合理的缓存过期时间:避免缓存数据长时间占用内存。
  2. 定期清理缓存:可在应用的空闲时间或者特定事件触发时,清理过期的缓存数据。例如,在路由切换时检查并清理部分缓存。
  3. 控制缓存数据量:对于频繁搜索的关键词,可以设置缓存数据的最大数量,当超出时,根据一定的策略(如LRU - 最近最少使用)删除旧的缓存数据。