Vue请求缓存导致数据更新不及时怎么办?

司空子格 阅读 62

最近在做Vue项目时遇到个奇怪的问题,我给接口设置了Cache-Control: max-age=300,但页面刷新时数据总比实际延迟很久。比如商品价格修改后,用户需要等很久才能看到新价格。

我试过手动清除localStorage的缓存,但发现有些接口数据还是会被浏览器缓存拦截。看代码发现请求组件是这样写的:


<template>
  <div>{{ product.price }}</div>
</template>

<script>
export default {
  data() {
    return {
      product: {}
    }
  },
  created() {
    axios.get('/api/product/1', {
      headers: { 'Cache-Control': 'no-cache' }
    }).then(res => this.product = res.data)
  }
}
</script>

明明设置了no-cache,为什么还是会被缓存?是不是Vue的响应式系统哪里没处理好?有没有更好的缓存策略既能减少请求又保证及时更新?

我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
打工人桂霞
你加的 Cache-Control: no-cache 是请求头,但浏览器缓存是看响应头的,服务端得返回 Cache-Control: no-storeno-cache 才生效,你前端加这个没用。

应该能用两种方案:要么后端改响应头加 no-store,要么前端加时间戳参数绕过缓存,比如 axios.get('/api/product/1?_t=' + Date.now())

如果想兼顾性能和实时性,建议用 etaglast-modified 做条件请求,配合 no-cache 响应头,这样没更新时返回 304,更新了才拉新数据。

created() {
axios.get('/api/product/1', {
params: { _t: Date.now() }
}).then(res => this.product = res.data)
}
点赞 2
2026-02-25 06:01
令狐爱景
问题出在请求头设置上,Cache-Control: no-cache 并不能完全禁用缓存,它只是告诉浏览器每次验证缓存是否过期。改成 Cache-Control: no-store 就能彻底禁用缓存。另外,接口的缓存策略应该在服务端和客户端都明确设置。

直接改代码:
axios.get('/api/product/1', {
headers: { 'Cache-Control': 'no-store' }
}).then(res => this.product = res.data)


如果想兼顾性能和实时性,可以加个时间戳参数强制刷新:axios.get('/api/product/1?timestamp=' + new Date().getTime()),或者在服务端调整缓存策略,比如返回 Cache-Control: must-revalidate, max-age=60。检查一下服务端响应头是不是覆盖了你的请求头设置。
点赞 3
2026-02-18 11:06