news 2026/4/25 5:49:00

Vue 中的 keep-alive 组件

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Vue 中的 keep-alive 组件

Vue 中的 keep-alive 组件

keep-alive是 Vue 内置的一个抽象组件,用于缓存不活动的组件实例,而不是销毁它们。这可以保留组件状态或避免重新渲染,从而提升性能。

核心特性

  1. 组件状态保持:当组件在<keep-alive>中切换时,其状态会被保留
  2. 避免重复渲染:缓存的组件不会重新创建,减少 DOM 操作
  3. 生命周期变化:添加了特殊的生命周期钩子

基本用法

<template> <div> <button @click="currentTab = 'TabA'">Tab A</button> <button @click="currentTab = 'TabB'">Tab B</button> <keep-alive> <component :is="currentTab"></component> </keep-alive> </div> </template> <script> export default { data() { return { currentTab: 'TabA' } }, components: { TabA: { template: '<div>Tab A Content <input placeholder="输入会被保留" /></div>' }, TabB: { template: '<div>Tab B Content</div>' } } } </script>

配置属性

1.include- 指定缓存组件
<!-- 字符串(逗号分隔) --> <keep-alive include="ComponentA,ComponentB"> <component :is="currentComponent"></component> </keep-alive> <!-- 正则表达式 --> <keep-alive :include="/ComponentA|ComponentB/"> <component :is="currentComponent"></component> </keep-alive> <!-- 数组 --> <keep-alive :include="['ComponentA', 'ComponentB']"> <component :is="currentComponent"></component> </keep-alive>
2.exclude- 排除不缓存组件
<keep-alive exclude="ComponentC"> <component :is="currentComponent"></component> </keep-alive>
3.max- 最大缓存实例数(Vue 2.5.0+)
<keep-alive :max="10"> <component :is="currentComponent"></component> </keep-alive>

生命周期钩子

<keep-alive>包裹的组件会获得两个额外的生命周期钩子:

activated
  • 组件被激活时调用
  • 当组件第一次渲染和每次从缓存中重新激活时都会触发
deactivated
  • 组件被停用时调用
  • 当组件被缓存时触发
<script> export default { name: 'MyComponent', activated() { console.log('组件被激活,恢复状态') // 例如:重新开始定时器 this.startTimer() }, deactivated() { console.log('组件被停用,进入缓存') // 例如:清除定时器 this.clearTimer() }, methods: { startTimer() { this.timer = setInterval(() => { console.log('定时器执行') }, 1000) }, clearTimer() { if (this.timer) { clearInterval(this.timer) } } }, // 传统生命周期依然有效 created() { console.log('created - 只在第一次创建时调用') }, mounted() { console.log('mounted - 只在第一次挂载时调用') } } </script>

与 Vue Router 结合使用

<template> <div id="app"> <!-- 缓存包含的路由组件 --> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <!-- 不缓存的路由组件 --> <router-view v-if="!$route.meta.keepAlive"></router-view> </div> </template>
// router.jsconstroutes=[{path:'/home',component:Home,meta:{keepAlive:true// 需要缓存}},{path:'/detail/:id',component:Detail,meta:{keepAlive:false// 不需要缓存}}]

高级用法示例

动态决定是否缓存
<template> <keep-alive :include="cachedComponents"> <router-view></router-view> </keep-alive> </template> <script> export default { data() { return { cachedComponents: [] // 动态维护需要缓存的组件名 } }, watch: { '$route'(to, from) { // 根据路由规则动态添加/移除缓存 if (to.meta.keepAlive && !this.cachedComponents.includes(to.name)) { this.cachedComponents.push(to.name) } } } } </script>
配合 transition 使用
<transition name="fade" mode="out-in"> <keep-alive> <component :is="currentComponent"></component> </keep-alive> </transition>

实现原理

keep-alive内部维护一个缓存对象,主要流程:

  1. 首次渲染时,创建组件实例并缓存
  2. 组件切换时,将当前组件标记为deactivated并隐藏
  3. 再次切回时,从缓存中取出实例,标记为activated并显示
  4. 使用 LRU(最近最少使用)算法管理缓存(当使用max时)

注意事项

  1. 组件必须有 name 选项includeexclude属性通过组件名匹配
  2. 避免内存泄漏:合理设置max,及时清理不需要的缓存
  3. 状态一致性:确保activated中恢复的状态是正确的
  4. 异步组件:同样支持,但需要注意加载时机
  5. 与 v-for 使用:不推荐同时使用,可能会导致缓存混乱

适用场景

  1. 标签页切换:保持每个标签页的状态
  2. 表单页面:离开后返回,表单数据不丢失
  3. 列表页 → 详情页:返回列表页时保持滚动位置和过滤条件
  4. 需要大量计算或网络请求的组件:避免重复计算/请求

Vue 3 中的变化

在 Vue 3 中,keep-alive的使用方式类似,但有细微变化:

  • includeexclude支持组件实例的namesetup函数中的name
  • 不再支持缓存<keep-alive>的直接子元素数组
<!-- Vue 3 --> <router-view v-slot="{ Component }"> <keep-alive> <component :is="Component" v-if="$route.meta.keepAlive" /> </keep-alive> <component :is="Component" v-if="!$route.meta.keepAlive" /> </router-view>

keep-alive是 Vue 中优化组件性能的重要工具,合理使用可以显著提升用户体验,特别是在需要保持组件状态的场景中。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/25 5:44:33

Qwen3-TTS开源

Qwen3-TTS&#xff08;通义千问3代文本转语音&#xff09;全家桶的开源&#xff0c;是阿里云在AI语音领域的重要布局&#xff0c;其意义不仅在于技术共享&#xff0c;更在于通过开放生态推动整个TTS&#xff08;Text-to-Speech&#xff0c;文本转语音&#xff09;技术的普及与创…

作者头像 李华
网站建设 2026/4/25 5:45:51

深度测评10个AI论文平台,继续教育学生轻松搞定毕业论文!

深度测评10个AI论文平台&#xff0c;继续教育学生轻松搞定毕业论文&#xff01; AI 工具如何重塑论文写作的未来 在当前继续教育学生面临日益繁重的学业压力下&#xff0c;AI 工具正逐渐成为他们高效完成毕业论文的重要助手。尤其是在降低 AIGC&#xff08;人工智能生成内容&am…

作者头像 李华
网站建设 2026/4/21 17:28:37

提升多尺度检测能力:YOLOv8 中 P2 小目标与 P6 超大目标检测头添加方法解析

蓝色线条为原模型,绿色线条为优化后的小目标模型,map提升4.5! 我们先理解什么叫做上下采样、再理解要选择哪一层作为检测头和分辨率越大检测目标越小等问题,然后再来添加小目标检测头就会容易理解很多! 原理介绍 一、上采样(Upsampling) 1. 定义 上采样是指将特征图…

作者头像 李华
网站建设 2026/4/22 6:37:35

混联混动汽车动力性经济性仿真:Cruise与Simulink联合探秘

cruise软件模型&#xff0c;混动仿真模型&#xff0c;cruise与simulink联合仿真模型&#xff0c;Cruise混动仿真模型&#xff0c;混联混动汽车动力性经济性仿真在汽车行业向着绿色、高效迈进的征程中&#xff0c;混联混动汽车凭借其独特的动力架构&#xff0c;成为了研究与发展…

作者头像 李华
网站建设 2026/4/23 14:17:09

关于阿里云 OSS 跨域配置不生效的真实原因与解决方案

关于阿里云 OSS 跨域配置不生效的真实原因与解决方案 关键词:阿里云 OSS 跨域不生效、OSS CORS 配置、阿里云 CDN 跨域、OSS 下载跨域、前端跨域问题 今天在测试阶段,测试同学给我提了一个 bug:素材下载不了。 一开始我以为是小问题,结果排查下来,发现这是一个非常容易被…

作者头像 李华