Vue中怎么给axios请求加缓存避免重复调用?

闲人颖杰 阅读 10

我在做商品详情页,每次切换tab都会重新请求相同的数据,明明数据没变却反复发请求,很浪费。试过用sessionStorage手动存,但感觉不够优雅,有没有更自动的方式?

现在代码是这样的:

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const product = ref(null)

onMounted(async () => {
  const res = await axios.get('/api/product/123')
  product.value = res.data
})
</script>

想在不改太多结构的前提下,给这个请求加上缓存,比如5分钟内相同URL就直接返回缓存结果,该怎么做?

我来解答 赞 7 收藏
二维码
手机扫码查看
1 条解答
Zz欢欢
Zz欢欢 Lv1
给axios加上缓存确实能让代码更清爽。这里有个不错的方案,直接封装个带缓存功能的axios实例。

先创建一个 cachedAxios.js 文件:

const cache = {}
const cachedAxios = async function(url) {
if (cache[url] && Date.now() - cache[url].timestamp < 5 * 60 * 1000) {
return Promise.resolve(cache[url].data)
}
try {
const res = await axios.get(url)
cache[url] = { data: res.data, timestamp: Date.now() }
return res.data
} catch (error) {
throw error
}
}
export default cachedAxios


然后在你的组件里这么用:

<script setup>
import { ref, onMounted } from 'vue'
import cachedAxios from './cachedAxios'

const product = ref(null)

onMounted(async () => {
const res = await cachedAxios('/api/product/123')
product.value = res
})
</script>


这个写法优雅多了吧?把缓存逻辑抽离出来,不用每个请求都手动处理sessionStorage。而且以后想改缓存策略也方便,比如改成LRU之类的。

说实话,这种小封装能让你省不少事,还能保持代码整洁。开发就该这样,能偷懒的地方就别硬抗。
点赞
2026-03-28 02:00