keep-alive的应用

126 阅读1分钟

1.keep-alive功能

1.1通过LRU算法更新组件缓存 1.2组件的缓存

2.下面是keep-alive的源码

    const slot = this.$slots.default
    const vnode: VNode = getFirstComponentChild(slot)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern
      const name: ?string = getComponentName(componentOptions)
      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
    remove(keys, key)
    keys.push(key)
  } else {
    // delay setting the cache until update
    this.vnodeToCache = vnode
    this.keyToCache = key
  }

  vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])

}

个人看法+术语:以上的源码中include、exclude、max,组件名与include不匹配或与exclude匹配都会直接退出并返回 VNode,将当前 VNode 缓存起来,并加入当前组件的 key。如果缓存组件的数量超出 max 的值,即缓存空间不足,组件的 keepAlive 标记为 true,表示它是被缓存的组件。pruneCacheEntry 负责将组件从缓存中删除,它会调用组件 $destroy 方法销毁组件实例,缓存组件置空,并移除对应的 key。