在正常的 Vue 渲染逻辑中,当你切换路由或动态组件时,旧组件会被销毁(Unmount),新组件会被挂载(Mount)。
这会带来两个显著问题:
keep-alive 缓存 组件实例(VNode)。
当组件被“销毁”时,它并不会真正从内存中被垃圾回收,而是被移动到一个隐藏的容器中。它保存了以下内容:
1.包裹动态组件
2.配合属性精细化控制 若不想缓存所有的组件,有三个关键参数:
3.路由级别使用
// vue3
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>// 简化版渲染流程
// 第一次渲染 Home 组件
<KeepAlive>
<Home />
</KeepAlive>
// KeepAlive 内部执行:
// 1. 检查 cache 中是否有 Home 的 vnode → 没有
// 2. 创建 Home 组件实例,存储到 cache
// 3. 渲染 Home 组件
// 切换到 About 组件
<KeepAlive>
<About />
</KeepAlive>
// KeepAlive 内部执行:
// 1. 检查 cache 中是否有 About 的 vnode → 没有
// 2. 创建 About 组件实例,存储到 cache
// 3. 将 Home 组件移动到隐藏容器(deactivate)
// 4. 渲染 About 组件
// 再次切换回 Home 组件
// 1. 检查 cache 中是否有 Home 的 vnode → 有!
// 2. 直接从 cache 取出 Home 的 vnode
// 3. 重新激活 Home 组件(触发 onActivated)
// 4. 不需要重新创建组件实例,保留之前的状态