vue 的 keep-alive 详解

server/2024/10/18 17:30:43/

目录

keep-alive 是什么?

keep-alive 属性

keep-alive 使用场景及用法

keep-alive 匹配规则

缓存实例的生命周期

缓存后如何获取数据

原理分析


keep-alive 是什么?

<KeepAlive> 是一个内置组件,它的功能是在多个组件间动态切换时缓存被移除的组件实例,而不是销毁它们,可防止重复渲染 DOM。

<keep-alive> 与 <transition>相似,只是一个抽象组件,它不会在 DOM 树中渲染(真实或者虚拟都不会),也不在父组件链中存在,比如:你在 this.$parent 中永远找不到 keep-alive 。

keep-alive 属性

属性名属性值描述
include字符串或正则表达式只有 name 匹配的组件会被缓存
exclude字符串或正则表达式任何 name 匹配的组件都不会被缓存
max数字最多可以缓存多少组件实例。

类似一个 LRU 缓存:如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间

keep-alive 使用场景及用法

使用原则:当我们在某些场景下不需要让页面重新加载时我们可以使用 keep-alive

当我们从首页–>列表页–>商详页–>再返回,这时候列表页应该是需要 keep-alive

首页–>列表页–>商详页–>返回到列表页(需要缓存)–>返回到首页(需要缓存)–>再次进入列表页(不需要缓存),这时候可以按需来控制页面的 keep-alive

  • 普通用法
    <template><div><keep-alive include="test-keep-alive"><!-- 将缓存 name 为 test-keep-alive 的组件 --><component></component></keep-alive><keep-alive include="a,b"><!-- 将缓存 name 为 a 或者 b 的组件,结合动态组件使用 --><component :is="currentComponent"></component></keep-alive><!-- 使用正则表达式,需使用v-bind --><keep-alive :include="/a|b/"><component :is="currentComponent"></component></keep-alive><!-- 动态判断 --><keep-alive :include="includedComponents"><router-view></router-view></keep-alive><keep-alive exclude="test-keep-alive"><!-- 将不缓存 name 为 test-keep-alive 的组件 --><component></component></keep-alive></div>
    </template><scripts>
    export default {name: 'test-keep-alive',data () {return {includedComponents: "test-keep-alive",currentComponent: 'test-keep-alive'}},watch: {// 监听 currentComponent 的变化,动态决定是否需要缓存currentComponent(newComponent, oldComponent) {if (/* 某些条件 */) {this.includedComponents.push(newComponent);} else {this.includedComponents = [];}}}
    }
    </scripts>
  • 结合 router,缓存部分页面
    // 使用 $route.meta 的 keepAlive 属性
    <keep-alive><router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    javascript">// 需要在 router 中设置 router 的元信息 meta
    //...router.js
    export default new Router({routes: [{path: '/',name: 'Hello',component: Hello,meta: {// 不需要缓存keepAlive: false }},{path: '/page1',name: 'Page1',component: Page1,meta: {// 需要被缓存keepAlive: true }}]
    })
  • 当然,也可以通过动态设置 route.meta 的 keepAlive 属性来实现其他需求。例如:首页是A页面。B页面跳转到A,A页面需要缓存。C页面跳转到A,A页面不需要被缓存。
    javascript">// A 路由
    {path: '/',name: 'A',component: A,meta: {keepAlive: true // 需要被缓存}
    }
    javascript">// B页面
    export default {data() {return {};},methods: {},beforeRouteLeave(to, from, next) {// 设置下一个路由的 meta// B 跳转到 A 时,让 A 缓存,即不刷新to.meta.keepAlive = true;  next();}
    };

思路:在每个路由的 beforeRouteLeave(to, from, next) 钩子中设置 to.meta.keepAlive

keep-alive 匹配规则

  •  首先匹配组件的 name 选项
  •  如果 name 选项不可用,则匹配它的局部注册名称(父组件 components 选项的键值)
  •  匿名组件,不可匹配(路由组件没有 name 选项,并且没有注册的组件名)
  •  只能匹配当前被包裹的组件,不能匹配更下面嵌套的子组件,例如:只能匹配路由组件的 name 选项,不能匹配路由组件里面的嵌套组件 name 选项
  •  不会在函数式组件中正常工作,因为他们没有缓存实例
  •  exclude 的优先级 > include

缓存实例的生命周期

当一个组件实例从 DOM 上移除但因为被 <KeepAlive> 缓存而仍作为组件树的一部分时,它将变为不活跃状态而不是被卸载。当一个组件实例作为缓存树的一部分插入到 DOM 中时,它将重新被激活

注意:

  • 这两个钩子只有组件被 keep-alive 包裹时才会被调用
  • 在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive 中,这两个钩子依然不会被调用
  • 在服务端渲染期间,这两个钩子也不会被调用
  • activated 在组件第一次渲染时会被调用,之后每次 keep-alive 被激活时调用
    javascript">// 第一次进入缓存路由/组件,在 mounted 后面,beforeRouteEnter 守卫传给 next 的回调函数之前
    beforeRouteEnter =>
    beforeCreate =>
    created =>
    beforeMount => 
    如果你是从别的路由/组件进来(组件销毁 destroyed/或离开缓存 deactivated) =>
    mounted => 
    activated 进入缓存组件 => 
    执行 beforeRouteEnter 回调// 因为组件被缓存了,再次进入缓存路由/组件时,不会触发这些钩子 beforeCreate create beforeMount mounted
    组件销毁destroyed /离开缓存 deactivated => 
    activated 进入当前缓存组件  => 
    执行 beforeRouteEnter 回调(组件缓存或销毁,嵌套组件的销毁和缓存也在这里触发)
    
  • deactivated 组件被停用(离开路由)时调用

    javascript">组件内的离开当前路由钩子 beforeRouteLeave =>  
    路由前置守卫 beforeEach =>
    全局后置钩子afterEach => 
    deactivated 离开缓存组件 => 
    activated 进入缓存组件(如果你进入的也是缓存路由)
    // 如果离开的组件没有缓存的话 beforeDestroy 会替换 deactivated 
    // 如果进入的路由也没有缓存的话  
    全局后置钩子 afterEach =>
    销毁 destroyed => 
    beforeCreate等

缓存后如何获取数据

解决方案可以有以下两种:

  • beforeRouteEnter:每次组件渲染的时候,都会执行 beforeRouteEnter

    javascript">beforeRouteEnter(to, from, next){next(vm=>{console.log(vm)// 每次进入路由执行vm.getData()  // 获取数据})
    },
  • actived:在keep-alive缓存的组件被激活的时候,都会执行actived钩子

    javascript">activated(){this.getData() // 获取数据
    },

原理分析

keep-alivevue中内置的一个组件

源码位置:src/core/components/keep-alive.js

javascript">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 = []},destroyed () {for (const key in this.cache) {pruneCacheEntry(this.cache, key, this.keys)}},mounted () {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)/* 获取该组件节点的componentOptions */const componentOptions = vnode && vnode.componentOptionsif (componentOptions) {/* 获取该组件节点的名称,优先获取组件的name字段,如果name不存在则获取组件的tag */const name = getComponentName(componentOptions)const { include, exclude } = this/* 如果name不在inlcude中或者存在于exlude中则表示不缓存,直接返回vnode */if ((include && (!name || !matches(include, name))) ||// excluded(exclude && name && matches(exclude, name))) {return vnode}const { cache, keys } = this/* 获取组件的key值 */const key = vnode.key == null// same constructor may get registered as different local components// so cid alone is not enough (#3269)? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : ''): vnode.key/*  拿到key值后去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存 */if (cache[key]) {vnode.componentInstance = cache[key].componentInstance// make current key freshestremove(keys, key)keys.push(key)}/* 如果没有命中缓存,则将其设置进缓存 */else {cache[key] = vnodekeys.push(key)// prune oldest entry/* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */if (this.max && keys.length > parseInt(this.max)) {pruneCacheEntry(cache, keys[0], keys, this._vnode)}}vnode.data.keepAlive = true}return vnode || (slot && slot[0])}
}

可以看到该组件没有 template,而是用了 render,在组件渲染的时候会自动执行 render 函数

this.cache 是一个对象,用来存储需要缓存的组件,它将以如下形式存储:

javascript">this.cache = {'key1':'组件1','key2':'组件2',// ...
}

在组件销毁的时候执行 pruneCacheEntry 函数

javascript">function pruneCacheEntry (cache: VNodeCache,key: string,keys: Array<string>,current?: VNode
) {const cached = cache[key]/* 判断当前没有处于被渲染状态的组件,将其销毁*/if (cached && (!current || cached.tag !== current.tag)) {cached.componentInstance.$destroy()}cache[key] = nullremove(keys, key)
}

在 mounted 钩子函数中观测 include 和 exclude 的变化,如下:

javascript">mounted () {this.$watch('include', val => {pruneCache(this, name => matches(val, name))})this.$watch('exclude', val => {pruneCache(this, name => !matches(val, name))})
}

如果include 或exclude 发生了变化,即表示定义需要缓存的组件的规则或者不需要缓存的组件的规则发生了变化,那么就执行 pruneCache 函数,函数如下:

javascript">function pruneCache (keepAliveInstance, filter) {const { cache, keys, _vnode } = keepAliveInstancefor (const key in cache) {const cachedNode = cache[key]if (cachedNode) {const name = getComponentName(cachedNode.componentOptions)if (name && !filter(name)) {pruneCacheEntry(cache, key, keys, _vnode)}}}
}

在该函数内对this.cache对象进行遍历,取出每一项的name值,用其与新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,则调用pruneCacheEntry函数将其从this.cache对象剔除即可

关于keep-alive的最强大缓存功能是在render函数中实现

首先获取组件的key值:

javascript">const key = vnode.key == null? 
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

拿到key值后去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存,如下:

javascript">/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
if (cache[key]) {vnode.componentInstance = cache[key].componentInstance/* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */remove(keys, key)keys.push(key)
} 

直接从缓存中拿 vnode 的组件实例,此时重新调整该组件key的顺序,将其从原来的地方删掉并重新放在this.keys中最后一个

this.cache对象中没有该key值的情况,如下:

javascript">/* 如果没有命中缓存,则将其设置进缓存 */
else {cache[key] = vnodekeys.push(key)/* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */if (this.max && keys.length > parseInt(this.max)) {pruneCacheEntry(cache, keys[0], keys, this._vnode)}
}

表明该组件还没有被缓存过,则以该组件的key为键,组件vnode为值,将其存入this.cache中,并且把key存入this.keys

此时再判断this.keys中缓存组件的数量是否超过了设置的最大缓存数量值this.max,如果超过了,则把第一个缓存组件删掉


http://www.ppmy.cn/server/23974.html

相关文章

Orange3数据可视化(箱线图-离散属性分布)

箱线图(Box Plot) 又称为盒须图、盒式图、盒状图或箱线图&#xff0c;是一种用作显示一组数据分散情况资料的统计图。因图形如箱子&#xff0c;且在上下四分位数之外常有线条像胡须延伸出去而得名 箱线图可以显示属性值的分布,快速发现异常,例如重复的值,离群值等,挖掘数据的…

大脑的工作原理

感知变化 我们自己的变化&#xff0c;大家有没有注意到&#xff0c;以前很活泼突然很沉默&#xff0c;以前很爱吃某一样东西&#xff0c;突然不爱吃。以前恐高&#xff0c;怕水&#xff0c;现在爱蹦极&#xff0c;会游泳.。 为什么会有这些变化&#xff1f; 因为我们的大脑也…

R语言 数据的整理与清洗(第一篇)

《Cookbook for R》 Manipulating Data ~ General Sorting 排序 1、vectors 向量 # 先随机生成一组向量 v <- sample(101:110)# 排序sort() sort(v) #> [1] 101 102 103 104 105 106 107 108 109 110# 反向排序 sort(v, decreasingTRUE) #> [1] 110 109 108 107 1…

2024年最新linux安装harbor

linux安装harbor Harbor官方介绍这里就不照搬了&#xff0c;说直白点&#xff1a;Harbor就是私有的 Docker Hob 镜像仓库。 前置条件&#xff1a;安装好docker,docker-compose 1、安装harbor离线包&#xff08;在线安装形式不稳定&#xff0c;由于网络原因中间可能中断&…

基于模糊控制的电动汽车锂电池SOC主动均衡电路MATLAB仿真模型

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; 模型简介 模型在 Matlab/Simulink仿真平台中搭建16节电芯锂电池电路模型&#xff0c;主要针对电动车锂电池组SOC差异性&#xff0c;采用模糊控制算法动态调节均衡电流&#xff0c;以减少均衡时间和能量损耗。…

git的学习笔记

git的学习使用 参考了书和好多网上搜到的连接&#xff0c;忘了记录参考的了&#xff0c;太多了&#xff08;&#xff09;捋出来一个大致的较为全面的git个人使用流程。 &#xff08;一&#xff09;基本操作&#xff1a; 安装配置好git 创建目录 init 初始化一个仓库&#xff0…

基础SQL 函数

在MySQL中内置了很多函数&#xff0c;我们可以通过一段程序或者代码直接调用这个函数 一、字符串函数 下面通过例子来验证这些函数 -- 字符串函数-- concat函数 select concat("hello ","world");-- lower函数 select lower("HELLO");-- upper函…

IOS 添加自动布局约束NSLayoutConstraint

自定义UICollectionViewCell&#xff0c;并添加自动布局约束。 #import "ViewChooseView.h"#pragma mark - Cellinterface ViewChooseViewCell : UICollectionViewCellproperty (nonatomic, strong) UILabel *showTemeLab; property (nonatomic, strong) UILabel *p…