node实现vue页面缓存
使用 keep-alive 组件实现缓存
在 Vue 中,可以通过 <keep-alive> 组件缓存动态组件或路由组件。在 template 中包裹需要缓存的组件:
<template>
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</template>
配置路由元信息
在 Vue Router 的路由配置中,通过 meta 字段标记需要缓存的页面:
const routes = [
{
path: '/page1',
component: Page1,
meta: { keepAlive: true } // 启用缓存
},
{
path: '/page2',
component: Page2,
meta: { keepAlive: false } // 不缓存
}
];
结合 Vue 生命周期钩子
被缓存的组件会触发 activated 和 deactivated 钩子,可用于数据刷新或清理:
export default {
activated() {
// 组件被激活时调用(从缓存中恢复)
this.fetchData();
},
deactivated() {
// 组件被停用时调用(进入缓存)
this.clearTimer();
}
};
动态控制缓存
通过 v-if 或 include/exclude 属性动态管理缓存:
<keep-alive :include="['Page1', 'Page2']">
<router-view />
</keep-alive>
include:匹配组件名的白名单exclude:匹配组件名的黑名单
Node 服务端配合
若需 SSR(服务端渲染),需在服务端模拟客户端缓存行为。例如,使用 lru-cache 库:
const LRU = require('lru-cache');
const cache = new LRU({ max: 100 });
app.use((req, res, next) => {
const key = req.url;
if (cache.has(key)) {
return res.send(cache.get(key));
}
// 未命中缓存时继续渲染
next();
});
缓存策略优化
- 按需缓存:结合路由守卫动态设置
meta.keepAlive。 - 缓存清理:通过
this.$destroy()强制销毁组件实例。 - SSR 缓存:根据用户会话或页面特征设置缓存键,避免数据污染。
注意事项
- 缓存可能导致内存增长,需合理设置缓存上限。
- 表单输入等状态会被保留,需手动重置或监听路由变化。
- 动态组件(如
:is)的缓存需确保组件名稳定。







