当前位置: 首页 > news >正文

keep-alive实现原理及Vue2/Vue3对比分析

一、keep-alive基本概念

keep-alive是Vue的内置组件,用于缓存组件实例,避免重复渲染。它具有以下特点:

  1. 抽象组件:自身不会渲染DOM,也不会出现在父组件链中
  2. 包裹动态组件:缓存不活动的组件实例,而不是销毁它们
  3. 生命周期:提供activated和deactivated钩子函数

二、keep-alive核心实现原理

1. 基本工作流程

  1. 判断当前组件是否需要缓存
  2. 生成组件唯一key
  3. 缓存组件实例
  4. 在被包裹组件上触发对应的生命周期钩子

2. 缓存策略

采用LRU(Least Recently Used)算法:

  • 设置最大缓存数量(max属性)
  • 优先删除最久未使用的组件
  • 新组件加入时,若达到上限则删除最旧组件

三、Vue2实现原理

// Vue2 中 keep-alive 的核心实现
export default {name: 'keep-alive',abstract: true, // 抽象组件标识props: {include: [String, RegExp, Array],exclude: [String, RegExp, Array],max: [String, Number]},created () {this.cache = Object.create(null) // 缓存对象this.keys = [] // 缓存key数组},destroyed () {// 销毁所有缓存实例for (const key in this.cache) {pruneCacheEntry(this.cache, key)}},mounted () {// 监听include和exclude的变化this.$watch('include', val => {pruneCache(this, name => matches(val, name))})this.$watch('exclude', val => {pruneCache(this, name => !matches(val, name))})},render () {const slot = this.$slots.defaultconst vnode = getFirstComponentChild(slot)const componentOptions = vnode && vnode.componentOptionsif (componentOptions) {const name = getComponentName(componentOptions)const { include, exclude } = this// 判断是否需要缓存if ((include && (!name || !matches(include, name))) ||(exclude && name && matches(exclude, name))) {return vnode}const { cache, keys } = thisconst key = vnode.key == null? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : ''): vnode.key// 命中缓存if (cache[key]) {vnode.componentInstance = cache[key].componentInstanceremove(keys, key)keys.push(key) // 调整key顺序} else {cache[key] = vnode // 缓存组件keys.push(key)// 超过max限制时清理最久未使用的组件if (this.max && keys.length > parseInt(this.max)) {pruneCacheEntry(cache, keys[0])keys.shift()}}vnode.data.keepAlive = true}return vnode || (slot && slot[0])}
}

四、Vue3实现原理

// Vue3 中 keep-alive 的核心实现
export const KeepAliveImpl = {name: 'KeepAlive',__isKeepAlive: true,props: {include: [String, RegExp, Array],exclude: [String, RegExp, Array],max: [String, Number]},setup(props, { slots }) {const cache = new Map() // 使用Map存储缓存const keys = new Set() // 使用Set存储keysconst current = getCurrentInstance()// 缓存子树const cacheSubtree = () => {if (current.subTree) {cache.set(current.subTree.key, current.subTree)keys.add(current.subTree.key)}}// 修剪缓存const pruneCache = (filter?: (name: string) => boolean) => {cache.forEach((vnode, key) => {const name = vnode.type.nameif (name && (!filter || filter(name))) {pruneCacheEntry(key)}})}// 清理缓存条目const pruneCacheEntry = (key: CacheKey) => {const cached = cache.get(key)if (!current || !isSameVNodeType(cached, current)) {unmount(cached)}cache.delete(key)keys.delete(key)}// 监听include/exclude变化watch(() => [props.include, props.exclude],([include, exclude]) => {include && pruneCache(name => matches(include, name))exclude && pruneCache(name => !matches(exclude, name))})// 卸载时清理所有缓存onBeforeUnmount(() => {cache.forEach(cached => {unmount(cached)})})return () => {const children = slots.default?.()if (!children) return nullconst vnode = children[0]if (!vnode) return nullconst comp = vnode.typeconst name = comp.name// 检查是否应该缓存if ((props.include && (!name || !matches(props.include, name))) ||(props.exclude && name && matches(props.exclude, name))) {return vnode}const key = vnode.key == null ? comp : vnode.keyconst cached = cache.get(key)// 命中缓存if (cached) {vnode.el = cached.elvnode.component = cached.component// 标记为kept-alivevnode.shapeFlag |= ShapeFlags.COMPONENT_KEPT_ALIVE} else {// 缓存新组件cache.set(key, vnode)keys.add(key)// 超过max限制时清理if (props.max && cache.size > parseInt(props.max)) {pruneCacheEntry(keys.values().next().value)}}// 标记keepAlivevnode.shapeFlag |= ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVEreturn vnode}}
}

五、Vue2和Vue3实现差异对比

1. 数据结构

  • Vue2: 使用普通对象和数组存储缓存
    this.cache = Object.create(null)
    this.keys = []
    
  • Vue3: 使用Map和Set存储缓存
    const cache = new Map()
    const keys = new Set()
    

2. 组件实现方式

  • Vue2: 选项式API,通过created、mounted等生命周期实现
  • Vue3: 组合式API,使用setup函数实现,逻辑更集中

3. 渲染机制

  • Vue2: 在render函数中直接操作VNode
  • Vue3: 使用新的渲染器架构,更好地支持Fragment和异步组件

4. 性能优化

  • Vue3优势:
    1. 更高效的响应式系统
    2. 更智能的编译优化
    3. 更好的Tree-shaking支持
    4. 更完善的TypeScript支持

5. 生命周期钩子

  • Vue2:
    export default {activated() {},deactivated() {}
    }
    
  • Vue3:
    import { onActivated, onDeactivated } from 'vue'setup() {onActivated(() => {})onDeactivated(() => {})
    }
    

六、使用方法案例

1. Vue2中的使用方法

基础用法
<!-- App.vue -->
<template><div id="app"><keep-alive><component :is="currentComponent"></component></keep-alive></div>
</template><script>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'export default {name: 'App',components: {ComponentA,ComponentB},data() {return {currentComponent: 'ComponentA'}}
}
</script>
配合路由使用
// router.js
import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)const routes = [{path: '/list',component: () => import('./views/List.vue'),meta: {keepAlive: true // 需要缓存的路由}},{path: '/detail',component: () => import('./views/Detail.vue'),meta: {keepAlive: false // 不需要缓存的路由}}
]export default new VueRouter({routes
})
<!-- App.vue -->
<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>
使用include和exclude
<template><div id="app"><keep-alive :include="['ComponentA', 'ComponentB']" :exclude="['ComponentC']"><router-view></router-view></keep-alive></div>
</template><script>
export default {name: 'App'
}
</script>

2. Vue3中的使用方法

基础用法
<!-- App.vue -->
<template><div id="app"><KeepAlive><component :is="currentComponent"></component></KeepAlive></div>
</template><script setup>
import { ref } from 'vue'
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'const currentComponent = ref('ComponentA')
</script>
配合路由使用
// router.ts
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/list',component: () => import('./views/List.vue'),meta: {keepAlive: true}},{path: '/detail',component: () => import('./views/Detail.vue'),meta: {keepAlive: false}}
]export default createRouter({history: createWebHistory(),routes
})
<!-- App.vue -->
<template><div id="app"><RouterView v-slot="{ Component }"><KeepAlive><component :is="Component" v-if="$route.meta.keepAlive" /></KeepAlive><component :is="Component" v-if="!$route.meta.keepAlive" /></RouterView></div>
</template><script setup>
import { RouterView } from 'vue-router'
</script>
使用include和exclude
<!-- App.vue -->
<template><div id="app"><RouterView v-slot="{ Component }"><KeepAlive :include="['ListPage']" :max="10"><component :is="Component" /></KeepAlive></RouterView></div>
</template><script setup>
import { RouterView } from 'vue-router'
</script>
在组件中使用生命周期钩子
<!-- ListPage.vue -->
<template><div class="list-page"><ul><li v-for="item in list" :key="item.id">{{ item.name }}</li></ul></div>
</template><script setup>
import { ref, onActivated, onDeactivated } from 'vue'const list = ref([])// 在组件被激活时触发
onActivated(() => {console.log('组件被激活')// 可以在这里恢复组件的状态,如滚动位置
})// 在组件被停用时触发
onDeactivated(() => {console.log('组件被停用')// 可以在这里保存组件的状态
})
</script>

七、总结

  1. 核心原理相同:

    • 都使用LRU缓存策略
    • 都支持include/exclude过滤
    • 都实现了组件缓存和重用
  2. 主要改进:

    • Vue3使用更现代的数据结构
    • 更清晰的代码组织方式
    • 更好的性能优化
    • 更强大的TypeScript支持
    • 更完善的错误处理机制
http://www.lqws.cn/news/465193.html

相关文章:

  • 1.20.1 服务器系统(windows,Rocky 和 Ubuntu )体验
  • 语法糖:编程中的甜蜜简化 (附 Vue 3 Javascript 实战示例)
  • 服务发现与动态负载均衡的结合
  • Java、PHP、C++ 三种语言实现爬虫的核心技术对比与示例
  • day44-硬件学习之arm启动代码
  • css上下滚动文字
  • 博图SCL语言GOTO语句深度解析:精准跳转
  • 第三章 线性回归与感知机
  • FastGPT:开启大模型应用新时代(4/6)
  • 使用 Telegraf 向 TDengine 写入数据
  • 升级到 .NET 9 分步指南
  • 软件工程概述:核心概念、模型与方法全解析
  • 以智能管控削减能耗开支,楼宇自控系统激活建筑运营价值增量
  • MolyCamCCD复古胶片相机:复古质感,时尚出片
  • maxcomputer 和 hologres中的EXTERNAL TABLE 和 FOREIGN TABLE
  • LeetCode-2390. 从字符串中移除星号
  • 力扣网C语言编程题:多数元素
  • DAY 38 Dataset和Dataloader类
  • 分布式锁的四种实现方式:从原理到实践
  • 高云GW5AT-LV60 FPGA图像处理板
  • React Native自定义底部弹框
  • Docker高级管理--容器通信技术与数据持久化
  • 华为云Flexus+DeepSeek征文|体验华为云ModelArts快速搭建Dify-LLM应用开发平台并创建b站视频总结大模型
  • Java ArrayList集合和HashSet集合详解
  • 【自动鼠标键盘控制器|支持图像识别】
  • 从代码学习深度学习 - 预训练BERT PyTorch版
  • 文本分类与聚类:让信息“各归其位”的实用方法
  • 最具有实际意义价值的比赛项目
  • CMS与G1的并发安全秘籍:如何在高并发的垃圾回收中保持正确性?
  • 【开源初探】基于 Qwen2.5VL的文档解析工具:docext