Vue3项目中如何存储和缓存来自CMS的接口请求数据?
解决方案
核心思路是实现sessionStorage的读写双向绑定:初始化时优先读取缓存内容直接渲染,后台异步请求更新数据与缓存,同时兼顾首屏加载速度和数据新鲜度。你之前的实现没有生效,是因为缺少两个关键步骤:初始化state时没有读取缓存的内容、图片数据,请求拿到新数据后也没有同步写入sessionStorage。
核心修改点
- 初始化响应式状态时优先从sessionStorage读取对应语言的缓存内容,直接渲染实现秒开
- 缓存key与locale绑定,避免多语言场景下缓存内容错乱
- axios请求成功后同步将最新解析后的内容、图片链接写入缓存,供下次加载使用
完整修改代码
脚本部分
<script setup> import {reactive} from 'vue'; import DOMPurify from "dompurify"; import marked from "marked"; const state = reactive({ // 给locale加默认值避免为空报错 locale: sessionStorage.locale || 'zh-CN', content: "", image: "" }) // 定义多语言对应的缓存key const cacheContentKey = `home_content_${state.locale}` const cacheImageKey = `home_image_${state.locale}` // 初始化优先读缓存,直接赋值实现无延迟渲染 if (sessionStorage.getItem(cacheContentKey)) { state.content = sessionStorage.getItem(cacheContentKey) } if (sessionStorage.getItem(cacheImageKey)) { state.image = sessionStorage.getItem(cacheImageKey) } axios.get('/home') .then(res => { const data = res.data[0] const newContent = DOMPurify.sanitize(marked(data['content_' + state.locale])) const newImage = 'storage/' + data['image'] // 更新响应式状态 state.content = newContent state.image = newImage // 写入缓存供下次加载使用 sessionStorage.setItem(cacheContentKey, newContent) sessionStorage.setItem(cacheImageKey, newImage) }) .catch(err => { console.log(err); console.log(err.response); }); </script>
模板优化(可选)
可以给背景图加默认占位色,避免缓存失效、首次加载时出现空白:
<template> <section id="home" class="home"> <div class="home-image" :style="{'background-image': `url(${state.image})`, 'background-color': '#f5f5f5'}"></div> <div v-html="state.content"></div> </section> </template>
可选扩展优化
- 如果需要实现跨标签页、关闭浏览器后仍保留缓存,可以把sessionStorage替换为localStorage
- 可以给缓存加过期时间控制:存缓存时同步写入时间戳,初始化时判断如果缓存超过设定时效(例如1小时)就丢弃缓存走正常请求流程,避免数据长时间不更新
- 后端Laravel接口可以配合返回Cache-Control头或ETag标识,进一步减少不必要的请求流量
内容的提问来源于stack exchange,提问作者Artur Müller Romanov
相关产品推荐
相关产品推荐

