Vue请求缓存导致数据更新不及时怎么办?
最近在做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的响应式系统哪里没处理好?有没有更好的缓存策略既能减少请求又保证及时更新?
Cache-Control: no-cache并不能完全禁用缓存,它只是告诉浏览器每次验证缓存是否过期。改成Cache-Control: no-store就能彻底禁用缓存。另外,接口的缓存策略应该在服务端和客户端都明确设置。直接改代码:
如果想兼顾性能和实时性,可以加个时间戳参数强制刷新:
axios.get('/api/product/1?timestamp=' + new Date().getTime()),或者在服务端调整缓存策略,比如返回Cache-Control: must-revalidate, max-age=60。检查一下服务端响应头是不是覆盖了你的请求头设置。