阅读vue源码-----内置组件篇(keep-alive)
2021-05-25 16:28
537 查看
1.前言:
<keep-alive>是vue实现的一个内置组件,也就是说vue源码不仅实现了一套组件化的机制,也实现了一些内置组件。
<keep-alive>官网介绍如下:
<keep-alive>是
Vue中内置的一个抽象组件,它自身不会渲染一个
DOM元素,也不会出现在父组件链中。当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
这句话的意思是说,我们可以把一些不常变动的组件或者需要缓存的组件用
<keep-alive>包裹起来,这样<keep-alive>就会帮我们把组件保存在内存中,而不是直接的销毁,这样做可以保留组件的状态或避免多次重新渲染,以提高页面性能;
<keep-alive>组件到底是如何实现这个功能的呢?本篇记录分析
<keep-alive>组件的内部实现原理。
2.用法回顾:
<keep-alive>组件可接收三个属性:
include
- 字符串或正则表达式。只有名称匹配的组件会被缓存。exclude
- 字符串或正则表达式。任何名称匹配的组件都不会被缓存。max
- 数字。最多可以缓存多少组件实例,一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。
3.实现原理:
<keep-alive>
组件的定义位于源码的 src/core/components/keep-alive.js
文件中,如下:
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< ad8 /span>.$watch('include', val => { pruneCache(this, name => matches(val, name)) }) this.$watch('exclude', val => { pruneCache(this, name => !matches(val, name)) }) }, render() { /* 获取默认插槽中的第一个组件节点 */ const slot = this.$slots.default const vnode = getFirstComponentChild(slot) /* 获取该组件节点的componentOptions */ const componentOptions = vnode && vnode.componentOptions if (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 } ad0 const { cache, keys } = this 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 if (cache[key]) { vnode.componentInstance = cache[key].componentInstance // make current key freshest remove(keys, key) keys.push(key) } else { cache[key] = vnode keys.push(key) // prune oldest entry 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></template>标签,取而代之的是它内部多了一个叫做
render的函数,所以它不是一个常规的模板组件,而是一个函数式组件。执行
<keep-alive>组件渲染的时候,就会执行到这个
render函数。了解了这个以后,接下来我们从上到下一步一步细细阅读。
#props
在
props选项内接收传进来的三个属性:
include、
exclude和
max。如下:
props: { include: [String, RegExp, Array], exclude: [String, RegExp, Array], max: [String, Number] }
include表示只有匹配到的组件会被缓存,而
exclude表示任何匹配到的组件都不会被缓存,
max表示缓存组件的数量,因为我们是缓存的
vnode对象,它也会持有 DOM,当我们缓存的组件很多的时候,会比较占用内存,所以该配置允许我们指定缓存组件的数量。
#created
在
created钩子函数里定义并初始化了两个属性:
this.cache和
this.keys。
created () { this.cache = Object.create(null) this.keys = [] }
this.cache是一个对象,用来存储需要缓存的组件,它将以如下形式存储:
this.cache = { 'key1':'组件1', 'key2':'组件2', // ... }
this.keys是一个数组,用来存储每个需要缓存的组件的
key,即对应
this.cache对象中的键值。
#destroyed
当
<keep-alive>组件 ad8 被销毁时,此时会调用
destroyed钩子函数,在该钩子函数里会遍历
this.cache对象,然后将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉并将其从
this.cache对象中剔除。如下:
destroyed () { for (const key in this.cache) { pruneCacheEntry(this.cache, key, this.keys) } } // pruneCacheEntry函数 function pruneCacheEntry (cache,key,keys,current) { const cached = cache[key] /* 判断当前没有处于被渲染状态的组件,将其销毁*/ if (cached && (!current || cached.tag !== current.tag)) { cached.componentInstance.$destroy() } cache[key] = null remove(keys, key) }
#mounted
在
mounted钩子函数中观测
include和
exclude的变化,如下:
mounted () { this.$watch('include', val => { pruneCache(this, name => matches(val, name)) }) this.$watch('exclude', val => { pruneCache(this, name => !matches(val, name) ad8 ) }) }
如果
include或
exclude发生了变化,即表示定义需要缓存的组件的规则或者不需要缓存的组件的规则发生了变化,那么就执行
pruneCache函数,函数如下:
function pruneCache (keepAliveInstance, filter) { const { cache, keys, _vnode } = keepAliveInstance for (const key in cache) { const cachedNode = cache[key] if (cachedNode) { const name = getComponentName(cachedNode.componentOptions) if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode) } } } } function pruneCacheEntry (cache,key,keys,current) { const cached = cache[key] if (cached && (!current || cached.tag !== current.tag)) { cached.componentInstance.$destroy() } cache[key] = null remove(keys, key) }
在该函数内对
this.cache对象进行遍历,取出每一项的
name值,用其与新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,则调用
pruneCacheEntry函数将这个已经不需要缓存的组件实例先销毁掉,然后再将其从
this.cache对象中剔除。
#render
接下来就是重头戏
render函数,也是本篇文章中的重中之重。以上工作都是一些辅助工作,真正实现缓存功能的就在这个
render函数里,接下来我们逐行分析它。
在
render函数中首先获取第一个子组件节点的
vnode:
/* 获取默认插槽中的第一个组件节点 */ const slot = this.$slots.default const vnode = getFirstComponentChild(slot)
由于我们也是在
<keep-alive>标签内部写 DOM,所以可以先获取到它的默认插槽,然后再获取到它的第一个子节点。
<keep-alive>只处理第一个子元素,所以一般和它搭配使用的有
component动态组件或者是
router-view。
接下来获取该组件节点的名称:
/* 获取该组件节点的名称 */ const name = getComponentName(componentOptions) /* 优先获取组件的name字段,如果name不存在则获取组件的tag */ function getComponentName (opts: ?VNodeComponentOptions): ?string { return opts && (opts.Ctor.options.name || opts.tag) }
然后用组件名称跟
include、
exclude中的匹配规则去匹配:
const { include, exclude } = this /* 如果name与include规则不匹配或者与exclude规则匹配则表示不缓存,直接返回vnode */ if ( (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode }
如果组件名称与
include规则不匹配或者与
exclude规则匹配,则表示不缓存该组件,直接返回这个组件的
vnode,否则的话走下一步缓存:
const { cache, keys } = this /* 获取组件的key */ const key = vnode.key == null ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key /* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */ if (cache[key]) { vnode.componentInstance = cache[key].componentInstance /* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */ remove(keys, key) keys.push(key) } /* 如果没有命中缓存,则将其设置进缓存 */ else { cache[key] = vnode keys.push(key) /* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */ if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode) } } /* 最后设置keepAlive标记位 */ vnode.data.keepAlive = true
首先获取组件的
key值:
const key = vnode.key == null? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key
拿到
key值后去
this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存:
/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */ if (cache[key]) { vnode.componentInstance = cache[key].componentInstance /* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */ remove(keys, key) keys.push(key) }
直接从缓存中拿
vnode的组件实例,此时重新调整该组件key的顺序,将其从原来的地方删掉并重新放在
this.keys中最后一个。
如果
this.cache对象中没有该
key值:
/* 如果没有命中缓存,则将其设置进缓存 */ else { cache[key] = vnode keys.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,如果超过了,则把第一个缓存组件删掉。
那么问题来了:为什么要删除第一个缓存组件并且为什么命中缓存了还要调整组件key的顺序?
这其实应用了一个缓存淘汰策略LRU:
LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。
它的算法是这样子的:
- 将新数据从尾部插入到
this.keys
中; - 每当缓存命中(即缓存数据被访问),则将数据移到
this.keys
的尾部; - 当
this.keys
满的时候,将头部的数据丢弃;
LRU的核心思想是如果数据最近被访问过,那么将来被访问的几率也更高,所以我们将命中缓存的组件
key重新插入到
this.keys的尾部,这样一来,
this.keys中越往头部的数据即将来被访问几率越低,所以当缓存数量达到最大值时,我们就删除将来被访问几率最低的数据,即
this.keys中第一个缓存的组件。这也就之前加粗强调的已缓存组件中最久没有被访问的实例会被销毁掉的原因所在。
OK,言归正传,以上工作做完后设置
vnode.data.keepAlive = true,最后将
vnode返回。
以上就是
render函数的整个过程。
#4. 生命周期钩子
组件一旦被
<keep-alive>缓存,那么再次渲染的时候就不会执行
created、
mounted等钩子函数,但是我们很多业务场景都是希望在我们被缓存的组件再次被渲染的时候做一些事情,好在
Vue提供了
activated和
deactivated两个钩子函数,它的执行时机是
<keep-alive>包裹的组件激活时调用和停用 56c 时调用,下面我们就通过一个简单的例子来演示一下这两个钩子函数,示例如下:
let A = { template: '<div class="a">' + '<p>A Comp</p>' + '</div>', name: 'A', mounted(){ console.log('Comp A mounted') }, activated(){ console.log('Comp A activated') }, deactivated(){ console.log('Comp A deactivated') } } let B = { template: '<div class="b">' + '<p>B Comp</p>' + '</div>', name: 'B', mounted(){ console.log('Comp B mounted') }, activated(){ console.log('Comp B activated') }, deactivated(){ console.log('Comp B deactivated') } } let vm = new Vue({ el: '##app', template: '<div>' + '<keep-alive>' + '<component :is="currentComp">' + '</component>' + '</keep-alive>' + '<button @click="change">switch</button>' + '</div>', data: { currentComp: 'A' }, methods: { change() { this.currentComp = this.currentComp === 'A' ? 'B' : 'A' } }, components: { A, B } })
在上述代码中,我们定义了两个组件
A和
B并为其绑定了钩子函数,并且在根组件中用
<keep-alive>组件包裹了一个动态组件,这个动态组件默认指向组件
A,当点击
switch按钮时,动态切换组件
A和
B。我们来看下效果:
从图中我们可以看到,当第一次打开页面时,组件
A被挂载,执行了组件
A的
mounted和
activated钩子函数,当点击
switch按钮后,组件
A停止调用,同时组件
B被挂载,此时执行了组件
A的
deactivated和组件
B的
mounted和
activated钩子函数。此时再点击
switch按钮,组件
B停止调用,组件
A被再次激活,我们发现现在只执行了组件
A的
activated钩子函数,这就验证了文档中所说的组件一旦被
<keep-alive>缓存,那么再次渲染的时候就不会执行
created、
mounted等钩子函数。
#5. 总结
本篇文章介绍了
Vue中的内置组件
<keep-alive>组件。
首先,通过简单例子介绍了
<keep-alive>组件的使用场景。
接着,根据官方文档回顾了
&l 123e t;keep-alive>组件的具体用法。
然后,从源码角度深入分析了
<keep-alive>组件的内部原理,并且知道了该组件使用了
LRU的缓存策略。
最后,观察了
<keep-alive>组件对应的两个生命周期钩子函数的调用时机。
读完这篇文章相信在面试中被问到
<keep-alive>组件的实现原理的时候就不慌不忙啦。
相关文章推荐
- 内置组件 && vue中强大的缓存机制之keep-alive
- Vue 内置组件keep-alive的使用示例
- vue.js内置组件之keep-alive组件使用
- Vue2.0 keep-alive 组件的最佳实践
- vue-router 实现组件的缓存之 keep-alive
- vue使用this.$bus+keep-alive解决组件间跳转传参,参数无法保存问题
- (vue.js)vue 父组件使用keep-alive和infinite-scroll导致在子组件触发父组件的infinite-scroll方法
- Vue动态组件、组件传值、keep-alive、scoped、axios、响应结构
- vue组件keep-alive的应用及原理
- vue动态组件-keep-alive
- vue中keep-alive组件的入门使用教程
- Vue匿名组件使用keep-alive后动态清除缓存
- VUE 中 keep-alive 的 --是什么-- 使用场景-- 作用-- 新增属性--动态组件--理解
- 详解vue组件的keep-alive
- vue中内置的组件(component transition transition-group keep-alive slot)
- vue.js 2.x 能否设置某个组件不被keep-alive 的解决方案
- keep-alive 内置组件元素:保留组件状态或避免重新渲染
- vue项目中如何使用keep-alive缓存组件
- vue里如何主动销毁keep-alive缓存的组件
- 前端面试题vue—(vuex工作流程、vue-router导航守卫、keep-alive组件、 v-show VS v-if、vue中key的作用、assets和static的区别)