Vue2源码阅读——keep-alive

361 阅读2分钟

keep-alive 是 Vue的内置组件, 它是一个抽象组件, 包裹动态组件, 会缓存不活动的组件实例,而不是销毁, 主要用于保留组件状态或避免重新渲染 当组件在 keep-alive 内被切换, 会触发 activeddeactived这两个生命周期函数;

Prop

  1. include: [String, RegExp, Array] 字符串/正则表达式/数组, 匹配需要被缓存的组件实例

  2. exclude: [String, RegExp, Array] 字符串/正则表达式/数组, 匹配不需要被缓存的组件实例

  3. max: [String, Number] 字符串数字/数字, 最多可以缓存多少个组件, 一旦数量达到了, 在新实例被创建之前, 已缓存组件中最久没有被访问的实例会被销毁掉

用法

  1. 基本用法
<keep-alive>
    <component :is="view"></component>
</keep-alive>
  1. 多个条件判断子组件
<keep-alive>
    <comp-a v-if="a > 1"></comp-a>
    <comp-b v-else></comp-b>
</keep-alive>
  1. 结合transition组件使用
<transition>
  <keep-alive>
    <component :is="view"></component>
  </keep-alive>
</transition>
  1. 属性include/exclude: 字符串/正则表达式/数组

    • 逗号分隔字符串
    <keep-alive include="a,b">
      <component :is="view"></component>
    </keep-alive>
    
    • 正则表达式
    <keep-alive :include="/a|b/">
      <component :is="view"></component>
    </keep-alive>
    
    • 数组
    <keep-alive :include="['a', 'b']">
        <component :is="view"></component>
    </keep-alive>
    

源码阅读

文件定位:: core/components/keep-alive.js

import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'
  1. 引入 isRegExp 用于检测是否是正则表达式; remove 用于删除 数组元素
// _toString = Object.prototype.toString
export function isRegExp (v: any): boolean {
  return _toString.call(v) === '[object RegExp]'
}
/**
 * Remove an item from an array.
 */
export function remove (arr: Array<any>, item: any): Array<any> | void {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}
  1. getFirstComponentChild 获取第一个子组件
export function getFirstComponentChild (children: ?Array<VNode>): ?VNode {
  if (Array.isArray(children)) {
    for (let i = 0; i < children.length; i++) {
      const c = children[i]
      if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
        return c
      }
    }
  }
}

注意

getFirstComponentChild: 并非获取 第一个子元素, 而是获取第一个自定义组件;

isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c)): 判断元素是否是 自定义组件(包含异步组件)

export function isAsyncPlaceholder (node: VNode): boolean {
  return node.isComment && node.asyncFactory
}
  <keep-alive>
    <div class="hah"></div>
    <demo>123213</demo>
  </keep-alive>

这行代码, getFirstComponentChild 返回的是: demo这个自定义组件


定义 CacheEntryCacheEntryMap 两个类型, 用于Flow类型检测

type CacheEntry = {
  name: ?string;
  tag: ?string;
  componentInstance: Component;
};

type CacheEntryMap = { [key: string]: ?CacheEntry };

获取组件名称, 返回 组件名称 或者 标签名

function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}

用于检测组件名是否在include/exlude

function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
  if (Array.isArray(pattern)) {
    return pattern.indexOf(name) > -1
  } else if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}
  1. pruneCache: includeexlude 发生变化的时候,用于更新 keep-alivecachekeys, 删除 不需要的 已缓存的组件
  2. pruneCacheEntry: 处理不需要缓存的组件, 并且更新 cachekeys
function pruneCache (keepAliveInstance: any, filter: Function) {
  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)
      }
    }
  }
}

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)
}

核心代码

graph TD
render(render 渲染) --> getFirstComponentChild(获取第一个组件 getFirstComponentChild)
getFirstComponentChild --> componentOptions(获取 componentOptions)
componentOptions -- 不存在 --> vnode(vnode或者第一个元素)
componentOptions -- 存在 --> getComponentName(获取组件名 getComponentName)
getComponentName --> checkAche(是否需要缓存)
checkAche -- 否 --> vnode1(vnode)
checkAche -- 是 --> checkKey(否则缓存过)
checkKey -- 是 --> updateKey(将vnode.componentInstance设置为缓存的组件/更新key在keys的位置)
checkKey -- 否 --> setCache(this.vnodeToCache = vnode this.keyToCache = key)

updateKey --> updateKeepAlive(vnode.data.keepAlive = true)
setCache --> updateKeepAlive --> vnode
graph TD
mounted(mounted 挂载) --> cacheVNode(cacheVNode 函数) --> vnodeToCache(获取vnodeToCache)
vnodeToCache -- 存在 --> updateCache(将当前组件保存到cache中,key保存到keys中)
vnodeToCache -- 不存在 --> return
updateCache --> checkMax(是否超过max)
checkMax -- 删除缓存的第一个组件 --> pruneCacheEntry  
checkMax -- 否 --> return
pruneCacheEntry --> checkCurrentVode(否是当前组件)
checkCurrentVode -- 是 --> UpdateCache(从缓存中删除)
checkCurrentVode -- 否 --> destroy(组件调用$destroy)--> UpdateCache(从缓存中删除)
update(update 组件更新) --> cacheVNode
destroyed(destroyed 组件销毁) -- 删除缓存的全部组件--> pruneCacheEntry
destroy --> deactivated(触发 deactivated 钩子函数)

根据上面的简化的流程图可以看出 keep-alive的流程,将流程抽象以下步骤:

  1. keep-alive 创建的时候, 初始化 cachekeys
  2. keep-alive 渲染的时候, 设置需要缓存的组件 vnodeToCachekeyToCache
  3. keep-alive 挂载和更新的时候, 将vnodeToCachekeyToCache保存到 cachekeys,并且 根据 max来删除长期未访问过的组件;
  4. keep-alive 挂载的时候 监听 includeexclude的变化,及时的更新 cachekeys
  5. 缓存的组件被销毁的时候, 回调用 组件的 deactivated钩子函数
const patternTypes: Array<Function> = [String, RegExp, Array]

export default {
  name: 'keep-alive', // keep-alive组件名称
  abstract: true, // 抽象组件

  props: {
    include: patternTypes, // include属性: [String, RegExp, Array]
    exclude: patternTypes, // exclude属性: [String, RegExp, Array]
    max: [String, Number] // max:  [String, Number] 最大数量
  },

  methods: {
    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
      }
    }
  },

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

  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

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

  updated () {
    this.cacheVNode()
  },

  render () {
    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])
  }
}