vue keepalive实现原理
Vue KeepAlive 实现原理
Vue 的 KeepAlive 组件通过缓存组件实例来避免重复渲染,提升性能。以下是其核心实现原理:
缓存机制
KeepAlive 组件内部维护一个缓存对象 cache,用于存储被缓存的组件实例。当组件切换时,KeepAlive 会根据条件决定是否从缓存中复用实例。
缓存对象的结构如下:
{
key: vnode,
...
}
其中 key 是组件的唯一标识,通常是组件的 name 或 tag。
生命周期钩子
KeepAlive 通过劫持组件的生命周期钩子实现缓存逻辑:
activated:组件被激活时调用,从缓存恢复状态。deactivated:组件被停用时调用,将状态保存到缓存。
VNode 处理
KeepAlive 在渲染过程中会处理组件的 VNode:
render () {
const slot = this.$slots.default
const vnode = getFirstComponentChild(slot)
const key = vnode.key
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
} else {
cache[key] = vnode
}
vnode.data.keepAlive = true
return vnode
}
LRU 缓存策略
默认情况下,KeepAlive 使用 LRU(最近最少使用)算法管理缓存。可以通过 max 属性限制缓存数量:
<KeepAlive max="10">
<component :is="currentComponent" />
</KeepAlive>
当缓存数量超过 max 时,最久未使用的实例会被销毁。
源码关键点
Vue 源码中 KeepAlive 的核心逻辑:
- 在
created钩子中初始化缓存对象和 keys 数组。 - 在
render中获取子组件 VNode 并处理缓存。 - 通过
patch过程触发组件的activated和deactivated钩子。
这种设计使得 KeepAlive 能够高效地管理组件状态,避免不必要的渲染开销。







