当前位置:首页 > VUE

node实现vue页面缓存

2026-02-22 17:20:29VUE

使用 vue-server-renderer 实现服务端缓存

在 Node.js 中通过 vue-server-renderercreateBundleRenderer 实现页面缓存。配置 cache 选项可缓存渲染结果,减少重复渲染开销。

const { createBundleRenderer } = require('vue-server-renderer')
const renderer = createBundleRenderer(serverBundle, {
  cache: require('lru-cache')({
    max: 1000, // 缓存最大条目数
    maxAge: 1000 * 60 * 15 // 缓存15分钟
  })
})

组件级缓存配置

在 Vue 组件中添加 serverCacheKey 函数或 name 属性,决定缓存键。组件需为纯静态或无依赖动态数据。

node实现vue页面缓存

export default {
  name: 'MyComponent',
  serverCacheKey: props => props.id, // 根据props.id生成缓存键
  props: ['id']
}

使用 micro-caching 优化高频请求

对高频访问页面采用短期缓存(1-2分钟),通过 lru-cache 快速响应重复请求。

node实现vue页面缓存

const microCache = new LRU({
  max: 100,
  maxAge: 1000 * 60 // 1分钟缓存
})

app.get('*', (req, res) => {
  const hit = microCache.get(req.url)
  if (hit) return res.end(hit)

  renderer.renderToString((err, html) => {
    if (!err) microCache.set(req.url, html)
    res.end(html)
  })
})

动态数据与缓存失效处理

对于含动态数据的页面,通过版本号或时间戳强制更新缓存。

// 在渲染上下文注入版本号
context.version = dataVersion

// 组件内根据版本更新缓存
serverCacheKey: props => `${props.id}::${this.$ssrContext.version}`

避免内存泄漏的缓存策略

限制缓存大小与存活时间,避免长期占用内存。lru-cache 会自动淘汰最久未使用的条目。

new LRU({
  max: 500, // 最大500条
  maxAge: 1000 * 60 * 30 // 30分钟自动失效
})

标签: 缓存页面
分享给朋友:

相关文章

vue 实现页面返回

vue 实现页面返回

实现页面返回的方法 在Vue中实现页面返回功能可以通过多种方式实现,以下是几种常见的方案: 使用Vue Router的go方法 通过Vue Router的go方法可以控制浏览器的历史记录导航。ro…

vue单页面实现登录

vue单页面实现登录

实现登录功能的基本步骤 在Vue单页面应用(SPA)中实现登录功能,通常需要结合前端和后端交互。以下是关键步骤和代码示例: 创建登录组件 开发一个独立的登录组件,包含表单元素如用户名和密码输入框,以…

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 属性实现页面跳转: window.location.href = 'https://example…

h5实现登录页面跳转页面跳转页面跳转页面

h5实现登录页面跳转页面跳转页面跳转页面

实现登录页面跳转的方法 在H5中实现登录页面跳转可以通过多种方式完成,以下是一些常见的方法: 使用JavaScript的window.location方法 通过JavaScript的window.l…

h5页面实现录音

h5页面实现录音

实现H5页面录音的方法 使用Web Audio API Web Audio API提供音频处理能力,结合getUserMedia可实现录音。核心步骤包括请求麦克风权限、创建音频上下文和处理音频流。…

vue实现转页面

vue实现转页面

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转可以通过多种方式,主要分为编程式导航和声明式导航两种。以下是具体实现方法: 使用 <router-link> 声明式导航 <…