当前位置:首页 > 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 属性,决定缓存键。组件需为纯静态或无依赖动态数据。

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

使用 micro-caching 优化高频请求

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

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 会自动淘汰最久未使用的条目。

node实现vue页面缓存

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

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

相关文章

vue实现关闭页面

vue实现关闭页面

关闭当前页面的方法 在Vue中关闭当前页面可以通过JavaScript的window.close()方法实现。该方法会关闭当前浏览器窗口或标签页。 methods: { closePage()…

vue实现页面截屏

vue实现页面截屏

使用html2canvas库实现截屏 安装html2canvas库 npm install html2canvas --save 在Vue组件中引入并使用 import html2canvas f…

vue实现动态显示页面

vue实现动态显示页面

动态显示页面的实现方法 在Vue中实现动态显示页面通常涉及数据绑定、条件渲染、列表渲染以及动态组件等技术。以下是几种常见的实现方式: 数据驱动视图 Vue的核心思想是数据驱动视图,通过修改数据自动更…

h5实现页面跳转页面

h5实现页面跳转页面

H5 实现页面跳转的方法 在 H5(HTML5)中,实现页面跳转可以通过多种方式完成,以下是常见的几种方法: 使用 <a> 标签 通过 HTML 的 <a> 标签实现页面跳转…

vue实现页面切换

vue实现页面切换

Vue 实现页面切换的方法 Vue 中实现页面切换通常使用 Vue Router,这是 Vue.js 官方的路由管理器。以下是几种常见的实现方式: 使用 Vue Router 的基本配置 安装 Vu…

jquery跳转页面

jquery跳转页面

jQuery 跳转页面方法 使用 jQuery 实现页面跳转可以通过多种方式完成,以下是几种常见的方法: 使用 window.location.href 进行跳转 $(document).read…