如果你也有兴趣想要了解一下具体内部怎么实现的或者说有一定的了解但是不够熟悉,那么正好你也可以一起巩固下
tips: 这样面试的时候你就可以大声的问别人这个知识点了?。
keepalive 是什么53f0c36d9619adcda0d52683f186ae16 是一个内置组件,它的功能是在多个组件间动态切换时缓存被移除的组件实例。
keepalive 功能keepalive 一词借鉴于 http 协议,在 http 协议里面 keepalive 又称持久连接,作用是允许多个请求/响应共用同一个 http 连接,解决了频繁的销毁和创建 http 连接带来的额外性能开销。而同理 vue 里的 keepalive 组件也是为了避免一个组件被频繁的销毁/重建,避免了性能上的开销。
// app.vue<test :msg="curtab" v-if="curtab === 'test'"></test><helloworld :msg="curtab" v-if="curtab === 'helloworld'"></helloworld><div @click="toggle">toggle</div>
上述代码可以看到,如果我们频繁点击 toggle 时会频繁的渲染 test/helloworld 组件,当用户频繁的点击时 test 组件需要频繁的销毁/渲染,这就造成很大的渲染性能损失。
所以为了解决这种性能开销,你需要知道是时候使用 keepalive 组件。
<keepalive> <component :is="curtab === 'test' ? test : helloworld" :msg="curtab"></component></keepalive><div @click="toggle">toggle</div>
可以看这个录屏,在首次加载后再次频繁的切换并没有重新销毁与挂载,而仅仅是将组件进行了失活(而不是销毁),渲染时只需要重新激活就可以,而不需重新挂载,如果要渲染的组件很大,那就能有不错的性能优化。
想要体验的话可以去看看这个例子?官方demo,其中数据会被缓存这个也需要在开发使用中去注意到的
如何实现实现原理其实很简单,其实就是缓存管理和特定的销毁和渲染逻辑,使得它不同于其他组件。
keepalive 组件在卸载组件时并不能真的将其卸载,而是将其放到一个隐藏的容器里面,当被激活时再从隐藏的容器中拿出来挂载到真正的 dom 上就行,这也就对应了 keepalive 的两个独特的生命周期activated和deactivated。
先来简单了解下组件的挂载过程所以在 keepalive 内的子组件在 mount 和 unmount 的时候会执行特定的渲染逻辑,从而不会去走挂载和销毁逻辑
具体实现(实现一个小而简单的 keepalive)keepalive 组件的属性const keepaliveimpl: componentoptions = { name: "keepalive", // 标识这是一个 keepalive 组件 __iskeepalive: true, // props props: { exclude: [string, array, regexp], include: [string, array, regexp], max: [string, number] } } // iskeepalive export const iskeepalive = (vnode: vnode): boolean => (vnode.type as any).__iskeepalive
keepalive 组件的 setup 逻辑以及渲染逻辑(重点看)// setup 接着上面的代码// 获取到当前 keepalive 组件实例const instance = getcurrentinstance()! as any;// 拿到 ctxconst sharedcontext = instance.ctx as keepalivecontext;// cache 缓存// key: vnode.key | vnode.type value: vnodeconst cache: cache = new map()// 需要拿到某些的 renderer 操作函数,需要自己特定执行渲染和卸载逻辑const { renderer: { p: patch, m: move, um: _unmount, o: { createelement } } } = sharedcontext// 隐藏的容器,用来存储需要隐藏的 domconst storeagecontainer = createelement('div')// 存储当前的子组件的缓存 keylet pendingkey: cachekey | null = nullsharedcontext.activate = (vnode, container, anchor) => { // keepalive 下组件激活时执行的 move 逻辑 move(vnode, container, anchor, 0 /* enter */)}sharedcontext.deactivate = (vnode) => { // keepalive 下组件失活时执行的 move 逻辑 move(vnode, storeagecontainer, null, 1 /* leave */)}return () => { // 没有子组件 if (!slots.default) { return null; } const children = slots.default() as vnode[]; const rawnode = children[0]; let vnode = rawnode; const comp = vnode.type as concretecomponent; const name = comp.displayname || comp.name const { include, exclude } = props; // 没有命中的情况 if ( (include && (!name || !matches(include, name))) || (exclude && name && matches(exclude, name)) ) { // 直接渲染子组件 return rawnode; } // 获取子组件的 vnode key const key = vnode.key == null ? comp : vnode.key; // 获取子组件缓存的 vnode const cachedvnode = cache.get(key); pendingkey = key; // 命中缓存 if (cachedvnode) { vnode.el = cachedvnode.el; // 继承组件实例 vnode.component = cachedvnode.component; // 在 vnode 上更新 shapeflag,标记为 component_kept_alive 属性,防止渲染器重新挂载 vnode.shapeflag |= shapeflags.component_kept_alive } else { // 没命中将其缓存 cache.set(pendingkey, vnode) } // 在 vnode 上更新 shapeflag,标记为 component_should_keep_alive 属性,防止渲染器将组件卸载了 vnode.shapeflag |= shapeflags.component_should_keep_alive // 渲染组件 vnode return vnode;}
keepalive组件 mount 时挂载 renderer 到 ctx 上在 keepalive 组件内会从 sharedcontext 上的 renderer 上拿到一些方法比如 move、createelement 等
function mountcomponent() { // ... if (iskeepalive(initialvnode)) { ;(instance.ctx as keepalivecontext).renderer = internals }}
子组件执行特定的销毁和渲染逻辑首先从上面可以看到,在渲染 keepalive 组件时会对其子组件的 vnode 上增加对应的 shapeflag 标志
比如component_kept_alive标志,组件挂载的时候告诉渲染器这个不需要 mount 而需要特殊处理
const processcomponent = ( n1: vnode | null, n2: vnode, container: rendererelement, anchor: renderernode | null, ) => { if (n1 == null) { // 在 keepalive 组件渲染时会对子组件增加 component_kept_alive 标志 // 挂载子组件时会判断是否 component_kept_alive ,如果是不会调用 mountcomponent 而是直接执行 activate 方法 if (n2.shapeflag & shapeflags.component_kept_alive) { ;(parentcomponent!.ctx as keepalivecontext).activate( n2, container, anchor ) } // ... } }
同理component_should_keep_alive标志也是用来在组件卸载的时候告诉渲染器这个不需要 unmount 而需要特殊处理。
const unmount: unmountfn = (vnode) => { // ... // 在 keepalive 组件渲染时会对子组件增加 component_should_keep_alive 标志 // 然后在子组件卸载时并不会真实的卸载而是调用 keepalive 的 deactivate 方法 if (shapeflag & shapeflags.component_should_keep_alive) { ;(parentcomponent!.ctx as keepalivecontext).deactivate(vnode) return }}
如何挂载activated和deactivated生命周期(生命周期相关可以不用重点看)首先这两个生命周期是在 keepalive 组件内独特声明的,是直接导出使用的。
export function onactivated( hook: function, target?: componentinternalinstance | null) { // 注册 activated 的回调函数到当前的 instance 的钩子函数上 registerkeepalivehook(hook, lifecyclehooks.activated, target)}export function ondeactivated( hook: function, target?: componentinternalinstance | null) { // 注册 deactivated 的回调函数到当前的 instance 的钩子函数上 registerkeepalivehook(hook, lifecyclehooks.deactivated, target)}
然后因为这两个生命周期会注册在 setup 里面,所以只要执行 setup 就会将两个生命周期的回调函数注册到当前的 instance 实例上
// renderer.ts// mount 函数逻辑const mountcomponent = (initialvnode, container, anchor, parentcomponent, parentsuspense, issvg, optimized) => { // ... const instance: componentinternalinstance = compatmountinstance || (initialvnode.component = createcomponentinstance( initialvnode, parentcomponent, parentsuspense )) // 执行 setup setupcomponent(instance)}// setupcomponent 处理 setup 函数值export function setupcomponent( instance: componentinternalinstance, isssr = false) { // ... const isstateful = isstatefulcomponent(instance) // ... const setupresult = isstateful // setupstatefulcomponent 函数主要功能是设置当前的 instance ? setupstatefulcomponent(instance, isssr) : undefined // ...}function setupstatefulcomponent( instance: componentinternalinstance){ if (setup) { //设置当前实例 setcurrentinstance(instance) // 执行组件内 setup 函数,执行 onactivated 钩子函数进行回调函数收集 const setupresult = callwitherrorhandling( setup, instance, errorcodes.setup_function, [__dev__ ? shallowreadonly(instance.props) : instance.props, setupcontext] ) // currentinstance = null; unsetcurrentinstance() }}
最后在执行sharedcontext.activate和sharedcontext.deactivate的时候将注册在实例上的回调函数取出来直接执行就ok了,执行时机在 postrender 之后
sharedcontext.activate = (vnode, container, anchor) => { // keepalive 下组件激活时执行的 move 逻辑 move(vnode, container, anchor, 0 /* enter */) // 把回调推入到 postflush 的异步任务队列中去执行 queuepostrendereffect(() => { if (instance.a) { // a是 activated 钩子的简称 invokearrayfns(instance.a) } })}sharedcontext.activate = (vnode, container, anchor) => { // keepalive 下组件失活时执行的 move 逻辑 move(vnode, container, anchor, 0 /* enter */) queuepostrendereffect(() => { if (instance.da) { // da是 deactivated 钩子的简称 invokearrayfns(instance.da) } })}export const enum lifecyclehooks { // ... 其他生命周期声明 deactivated = 'da', activated = 'a',}export interface componentinternalinstance {// ... 其他生命周期[lifecyclehooks.activated]: function[][lifecyclehooks.deactivated]: function[]}
以下是关于上述demo如何实现的简化流程图
需要注意的知识点1、什么时候缓存keepalive 组件的onmounted和onupdated生命周期时进行缓存
2、什么时候取消缓存缓存数量超过设置的 max 时
监听 include 和 exclude 修改的时候,会读取缓存中的知进行判断是否需要清除缓存修剪缓存的时候也要 unmount(如果该缓存不是当前组件)或者 resetshapeflag 将标志为从 keepalive 相关 shapeflag 状态重置为 stateful_component 状态(如果该缓存是当前组件,但是被exclude了),当然 unmount 函数内包含 resetshapeflag 操作
3、缓存策略keepalive 组件的缓存策略是 lru(last recently used)缓存策略
核心思想在于需要把当前访问或渲染的组件作为最新一次渲染的组件,并且该组件在缓存修剪过程中始终是安全的,即不会被修剪。
看下面的图更加直观,图片来源一篇讲keepalive 缓存优化的文章
4、如何添加到 vue devtools 组件树上sharedcontext.activate = (vnode, container, anchor) => { // instance 是子组件实例 const instance = vnode.component! // ... // dev环境下设置, 自己模拟写的 devtools.emit('component:added', instance.appcontext.app, instance.uid, instance.parent ? instance.parent.uid: undefined, instance) // 官方添加 if (__dev__ || __feature_prod_devtools__) { // update components tree devtoolscomponentadded(instance) }}// 同理 sharedcontext.deactivates 上也要添加,不然不会显示在组件树上
5、缓存的子组件 props 更新处理当子组件有 prop 更新时是需要重新去 patch 的,所以在 activate 的时候需要重新执行 patch 进行子组件更新
sharedcontext.activate = (vnode, container, anchor) => { // ... // props 改变需要重新 patch(update) patch( instance.vnode, vnode, container, anchor, instance, parentsuspense, issvg, vnode.slotscopeids, optimized )}
(学习视频分享:web前端开发、编程基础视频)
以上就是一文聊聊vue中的keepalive组件的详细内容。
