都知道keep-alive是用于vue中组件缓存的,那内部如何实现缓存的呢,一起来看看吧
先放简单的文章导图:
1.keep-alive 在vue中起到什么作用
先来看看官网对keep-alive的一些功能说明:
组件之间切换的时候,你有时会想保持这些组件的状态,以避免反复重渲染导致的性能问题。
就可以使用到keep-alive,它可以用来进行动态组件的缓存
- 组件复用,提高性能
- 缓存不太使用的组件,而不是直接销毁
2.实际项目如何使用
2.1正常情况下组件跳转
在项目中用到的比较多的,就是使用动态路由。下面举个栗子:
直接使用命令 vue create hello-world 创建一个新的项目
几个文件稍微改动一下,主要看router 和view下面的两个home about 组件,在这两个路由组件进行跳转的时候,组件会销毁
效果如下:
当我们尝试切换(已经填了数据的)组件的时候,destroyed()函数,组件销毁,里面的数据也没有了。
代码如下
App.vue:
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view/>
</div>
</template>
router/index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
routes
})
export default router
view/about.vue:
<template>
<div class="about">
<input type="text">
</div>
</template>
<script>
export default {
name:"about",
destroyed() {
console.log('组件被销毁')
}
}
</script>
view/home.vue:
<template>
<div class="home">
<input type="text">
</div>
</template>
<script>
export default {
name: 'home',
destroyed() {
console.log('组件被销毁')
}
}
</script>
2.2 使用keep-alive 缓存组件
当跳转组件的时候,能缓存之前的组件,不销毁
只需修改上面的App.vue组件即可:
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<keep-alive>
<router-view />
</keep-alive>
</div>
</template>
2.3 keep-alive 控制组件是否缓存
在实际项目开发的时候,我们可能需要具体的某个项目可以进行缓存,那么如何通过keep-alive来实现呢?
keep-alive的参数有以下三种:
- include: [String,RegExp,Array] 只有匹配到的组件才能进行缓存
<keep-alive include="home">
<router-view />
</keep-alive>
- exclude:[String,RegExp,Array] 匹配到的组件都不缓存
<keep-alive include="about">
<router-view />
</keep-alive>
- max: [String,Number] 数字,最多能缓存多少组件实例。在新实例创建之前,缓存中最就没有使用的实例会被销毁
3.keep-alive 中源码是如何实现缓存
源码在这:
主要是分析下面的cacheVNdoe 以及生命周期钩子 render函数,下面一起来看看吧(大部分都在注释里面)
3.1 cacheVNode()
cacheVNode() {
const { cache, keys, vnodeToCache, keyToCache } = this
if (vnodeToCache) {
const { tag, componentInstance, componentOptions } = vnodeToCache
cache[keyToCache] = {
name: getComponentName(componentOptions),
tag,
componentInstance,
}
keys.push(keyToCache)
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
this.vnodeToCache = null
}
}
3.2 created():
定义两个属性
this.cache = Object.create(null)
this.keys = []
this.cache是一个对象,用来存储需要缓存的组件
this.cache = {
'key1':'组件1',
'key2':'组件2'
、、、
}
this.keys是以一个数组,用来存储每个需要缓存的组件的key,即对应this.cache对象中的键值。
3.3 destoryed()
该钩子会遍历this.cache对象,然后将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉,并将其从this.cache对象中移除
destoryed() {
for (const key in this.cache) {
pruneCacheEntery(this.cache,key,this.keys);
}
}
function pruneCacheEntery(cache,key,keys,current) {
const cached = cache[key]
if (cached &&& (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destory()
}
cache[key] = null
remove(keys,key)
}
3.4 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))
})
}
3.5 render()
keep-alive如何实现缓存
- 获取第一个子组件的节点
const slot = this.$solts.default
const vnode = getFirstComponentChild(solt)
只处理第一个子元素,所以一般和它搭配使用的有 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 中的普配规则取匹配
- 如果name与index规则不匹配或者与exclude规则匹配,表示不缓存该组件,直接返回这个组件的vnode就可以
const { include, exclude } = this
if (
(include && (!name || !matches(include, name))) ||
(exclude && name && !matches(exclude,name))
) {
return vnode
}
- 否则进行缓存
const { cache, keys } = this
// 获取组件的key值
const key = vnode.key == null?
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key
//拿到key值后取this.cach对象中寻找是否有该值,如果有,说明组件有缓存,命中缓存
/* 如果命中缓存,则直接从缓存中拿 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)
}
}
// 如果没有,则将组件存入缓存
LRU 最近最少使用
当使用keep-alive后,组件将不会进行created和mounted,但是有的时候我们需要在组件里面执行一定的操作,用的是activated和deactivated 两个钩子函数,它的执行时机是 包裹的组件激活时调用和停用时调用
4. LRU 缓存机制
调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个
,在上面的注释中,有这么一句话,把这个现在用了的节点从原先的地方删掉,再放到最后一个,这是啥意思?
其实这就是LRU缓存机制的核心,LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。
最后的最后,来一道力扣算法题:
LRU缓存
var LRUCache = function(capacity) {
this.size = capacity //缓存大小
this.map = new Map() // 使用map作为缓存结构
};
// LRUCache的原型对象上有两个方法 get(获取值) 和 put(修改/增加值)
LRUCache.prototype.get = function(key) {
// 如果get取的这个值之前就在map里面,需要把原先位置删掉,再把这个值重新加入,再返回要获取的这个值
if(this.map.has(key)){
let value = this.map.get(key) // 先缓存值
this.map.delete(key) // 删除
this.map.set(key, value) // 重新加入
return value
} else { // 不存在直接返回 -1
return -1
}
};
// 如果之前就存在,直接删除,再加入,
// 如果之前不存在再加入(再加入的过程中要先判断它的大小是否超出,
// 如果超出就要再加入这个数据之前,
// 把map里面那个最久没有使用的先删掉,再加入需要加入的值)
LRUCache.prototype.put = function(key, value) {
if(this.map.has(key)){ // 存在就先删除
this.map.delete(key)
}
this.map.set(key, value) // 加入
if(this.map.size > this.size){ // 超出就删除 先加入的
// 找到map中的第一条
this.map.delete(this.map.keys().next().value)
}
};
5. 总结
- keep-alive 是vue的一个内置组件,主要是用来控制组件的缓存,它可以设置三个参数,来设置哪个组件需要被缓存,或者不被缓存,同时还有设置最大的缓存大小
- 在分析keep-alive的缓存策略是,使用的是LRU缓存淘汰策略。
- LRU缓存策略的核心,主要是每次被访问(读取或修改)的那个数据,被期望是之后被用到的概率最大的那个数据,因此需要做处理
以上就是有关对keep-alive这个知识点的一些总结和归纳
有问题欢迎评论区指正
我是婧大
wx:lj18379991972 希望能和你一起学习前端