Redis缓存怎么在Vue里配合后端做数据更新?

Des.保霞 阅读 40

我用Vue写了个商品列表页,每次进页面都调接口拿数据,后端说加了Redis缓存,但改完商品信息后前端还是显示旧的。我试过在编辑成功后重新请求列表,但有时候还是刷不出来最新的,是不是缓存没清?

这是我的列表获取代码:

<script>
export default {
  async mounted() {
    const res = await this.$http.get('/api/products');
    this.products = res.data;
  },
  methods: {
    async updateProduct(id, data) {
      await this.$http.put(/api/products/${id}, data);
      // 这里重新拉一次列表,但偶尔还是旧数据
      this.mounted();
    }
  }
}
</script>
我来解答 赞 15 收藏
二维码
手机扫码查看
2 条解答
Des.庆敏
这问题根本不在前端,是后端更新商品后没清Redis缓存。

你前端刷新一百遍也没用,后端从缓存里读的还是旧数据。解决方案有两个:

1. 让后端在update接口里同时清除或更新对应商品的缓存(推荐,后端该干的活)
2. 前端这边想临时解决,可以在请求列表时加个时间戳参数绕过缓存:

async updateProduct(id, data) {
await this.$http.put(/api/products/${id}, data);
// 别调mounted,直接调获取列表的方法,加个时间戳
await this.fetchProducts();
},
async fetchProducts() {
const res = await this.$http.get(/api/products?_t=${Date.now()});
this.products = res.data;
}


不过这只是个hack,真正的问题是后端缓存策略没做好,让他们改改。
点赞
2026-03-18 19:04
浩轩 Dev
这明显是后端缓存失效问题啊。试试在更新商品后让后端清除对应缓存,或者在get请求加个随机参数强制刷新:

async mounted() {
const res = await this.$http.get(/api/products?t=${Date.now()});
this.products = res.data;
}


另外让后端检查下缓存策略,更新数据时要及时清除缓存,不然迟早出问题...困死了我先去喝杯咖啡
点赞 2
2026-03-05 12:07