对于keep-alive的理解

193 阅读4分钟

今天学习了一下vue中的keep-active,大体看了一下keep-active的源码对于今天的学习做一下总结。以下是个人的浅显理解,如有错误请指正。谢谢。

117.jpg

什么是keep-alive

在平常开发中,有部分组件没有必要多次初始化,这时我们就需要用到keep-alive来缓存;使组件的状态维持不变,在下一次展示是,也不会进行重新初始化组件

keep-alive可以用在很多地方。可以用来优化我们的页面。就比如在一个展示型的页面中没有必要重复调取接口,发送请求就可以使用keep-alive是组件的状态维持不变,在下次展示是不会重新初始化组件。

keepalive是vue内置的一个组件,可以是被包含的组件保存状态,或避免重复渲染。也就是所谓的组件缓存。

是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM

 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和  相似, 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。

    this.cache = Object.create(null) // {}
    this.keys = [] // []
  },

先执行created 这段代码的意思我个人理解是

1.创建一个空对象 缓存虚拟dom

2.创建一个放字符串的数组 缓存的虚拟dom健的集合

methods: {
    cacheVNode() {
      // {} []  VNode key
      const { cache, keys, vnodeToCache, keyToCache } = this
      if (vnodeToCache) {
        const { tag, componentInstance, componentOptions } = vnodeToCache
        // 把当前缓存的对象挂到 cache 对象 
        cache[keyToCache] = {
          name: getComponentName(componentOptions),
          tag,
          componentInstance,
        }
        // 把 key 添加到缓存 keys 数组里
        keys.push(keyToCache)
        // prune oldest entry
        // 最大缓存数  keys 长度 大于 最大缓存数
        // LRU 缓存淘汰算法
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
        // 清除 vnodeToCache 这个变量
        this.vnodeToCache = null
      }
    }
  },
destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

删除缓存VNode还要对应执行组件实例的destory钩子函数。

/**
 * 清除缓存
 */
function pruneCacheEntry (
  cache: CacheEntryMap,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const entry: ?CacheEntry = cache[key] 
  // 如果缓存对象 没有实例或者 当前缓存的标签不等于当前标签
  if (entry && (!current || entry.tag !== current.tag)) {
    // 强制销毁
    entry.componentInstance.$destroy()
  }
  // 清空
  cache[key] = null
  // 删除
  remove(keys, key)
}

pruneCacheEntry函数删除。

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

在mounted这个钩子中对include和exclude参数进行监听,然后实时地更新(删除)this.cache对象数据。pruneCache函数的核心也是去调用pruneCacheEntry。

/**
 * 修正缓存
 */
function pruneCache (keepAliveInstance: any, filter: Function) {
  // 当前 keep-alive 实例  缓存 key 数组 当前虚拟NODE
  const { cache, keys, _vnode } = keepAliveInstance

  // 对于不需要缓存的组件及时清除
  for (const key in cache) {
    const entry: ?CacheEntry = cache[key]
    if (entry) {
      const name: ?string = entry.name
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

render () {
    // 获取插槽的默认元素 this.$slots
    const slot = this.$slots.default
    // 获取第一个缓存的组件
    const vnode: VNode = getFirstComponentChild(slot)
    // 拿出当前组件的 options 选项
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern

      // 获取组件名称
      const name: ?string = getComponentName(componentOptions)

      // 获取组件传过来的 props 包含 未包含
      const { include, exclude } = this
      if (
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }

      const { cache, keys } = this
      const key: ?string = 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
         // LRU 缓存淘汰算法
        remove(keys, key)
        keys.push(key)
      } else {
        // delay setting the cache until update
        // 缓存当前的组件实例
        this.vnodeToCache = vnode
        // 缓存当前组件的 key
        this.keyToCache = key
      }

      vnode.data.keepAlive = true
    }
    // 返回组件实例 返回插槽第一个元素
    return vnode || (slot && slot[0])
  }

我感觉在这一段中render函数起到了至关重要的作用

那我们先来了解一下render函数是什么?

简单的说,在vue中我们使用模板HTML语法组建页面,使用rendtemplate模板时也要转译成VNod的函数,而用render函数构建DOM,vue就免去了转译的过程。

详情请看Vue 中render 函数的作用是什么 - web开发 - 亿速云 (yisu.com)

那么根据这篇文章就可以看出render一般是用来创建动态组件方式

render的执行时机:是在created之后 在methods之前。 以下是引用CSDN博主「看把你给能的。」的原创文章,来解释一下render函数的作用

  • 第一步:获取keep-alive包裹着的第一个子组件对象及其组件名;
  • 第二步:根据设定的黑白名单(如果有)进行条件匹配,决定是否缓存。不匹配,直接返回组件实例(VNode),否则执行第三步;
  • 第三步:根据组件ID和tag生成缓存Key,并在缓存对象中查找是否已缓存过该组件实例。如果存在,直接取出缓存值并更新该key在this.keys中的位置(更新key的位置是实现LRU置换策略的关键),否则执行第四步;
  • 第四步:在this.cache对象中存储该组件实例并保存key值,之后检查缓存的实例数量是否超过max的设置值,超过则根据LRU置换策略删除最近最久未使用的实例(即是下标为0的那个key)。
  • 第五步:最后并且很重要,将该组件实例的keepAlive属性值设置为true。 最后就是再次渲染执行缓存和对应钩子函数了

———————————————— 版权声明:本文为CSDN博主「看把你给能的。」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/weixin_4246…