vue keep alive 实现
Vue Keep-Alive 实现
Vue 的 keep-alive 是一个内置组件,用于缓存动态组件或路由组件,避免重复渲染和销毁,从而提升性能。以下是其核心实现方式和用法。
基本用法
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
keep-alive 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
结合路由使用
在 Vue Router 中,可以通过 keep-alive 缓存路由组件:

<keep-alive>
<router-view></router-view>
</keep-alive>
缓存特定组件
通过 include 或 exclude 属性指定需要缓存或排除的组件:
<keep-alive include="ComponentA,ComponentB">
<component :is="currentComponent"></component>
</keep-alive>
include:匹配组件名称(字符串或正则),仅缓存匹配的组件。exclude:排除匹配的组件,不缓存。
生命周期钩子
被缓存的组件会触发特定的生命周期钩子:

activated:组件被激活时调用(从缓存中重新显示)。deactivated:组件被停用时调用(进入缓存)。
export default {
activated() {
console.log('Component activated');
},
deactivated() {
console.log('Component deactivated');
}
};
实现原理
keep-alive 的核心原理是通过 Vue 的抽象组件机制:
- 在
created钩子中初始化缓存对象this.cache和键名数组this.keys。 - 在
render阶段,通过vnode.key或组件名称生成唯一标识,检查缓存中是否存在该组件。 - 若存在,直接返回缓存的实例;否则缓存当前组件实例。
- 通过
max属性限制缓存数量,超出时清除最久未使用的缓存。
自定义缓存策略
可以通过 cache 属性自定义缓存逻辑:
const customCache = {
get(key) {
// 自定义获取逻辑
},
set(key, vnode) {
// 自定义存储逻辑
}
};
<keep-alive :cache="customCache">
<component :is="currentComponent"></component>
</keep-alive>
注意事项
- 被缓存的组件需设置唯一的
name选项,否则include/exclude可能不生效。 - 频繁切换的组件适合缓存,但需注意内存占用问题。
- 通过
max属性限制缓存数量,避免内存泄漏:
<keep-alive max="5">
<router-view></router-view>
</keep-alive>






