keep-alive實現原理

使用說明

keep-alive組件接受三個屬性參數:includeexcludemaxvue

  • include 指定須要緩存的組件name集合,參數格式支持String, RegExp, Array。當爲字符串的時候,多個組件名稱以逗號隔開。
  • exclude 指定不須要緩存的組件name集合,參數格式和include同樣。
  • max 指定最多可緩存組件的數量,超過數量刪除第一個。參數格式支持String、Number。

源碼解析

keep-alive實例會緩存對應組件的VNode,若是命中緩存,直接從緩存對象返回對應VNode。node

import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'

type VNodeCache = { [key: string]: ?VNode };

function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}
//@doc 
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
}

function pruneCache (keepAliveInstance: any, filter: Function) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const cachedNode: ?VNode = cache[key]
    if (cachedNode) {
      const name: ?string = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const cached = cache[key]
  if (cached && (!current || cached.tag !== current.tag)) { //@doc 銷燬緩存裏的組件
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

const patternTypes: Array<Function> = [String, RegExp, Array] //@doc 支持字符串、正則、數組格式

export default {
  name: 'keep-alive',
  abstract: true,

  props: {
    include: patternTypes,
    exclude: patternTypes,
    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.$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 //@doc 獲取keep-alive裏面的內容
    const vnode: VNode = getFirstComponentChild(slot) //@doc 獲取第一個組件
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern
      const name: ?string = getComponentName(componentOptions)
      const { include, exclude } = this
      //@doc 從匹配規則能夠看出exclude的優先級比include高
      if (
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {  //@doc 若是設置了不緩存,直接返回vnode
        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 {  //@doc 若是不存在,存儲緩存對象
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {  //@doc 超過最大數,刪除第一個
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

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

router-view中keep-alive

router-view渲染組件時候,會判斷當前組件是否被緩存,若是被緩存,直接使用緩存的組件。vue-router中源碼vue-router

//@doc 判斷是否背keep-alive緩存
if (vnodeData.keepAlive && parent._inactive) {
  inactive = true
}
//@doc 若是組件被緩存,直接使用緩存裏組件
if (inactive) { 
  return h(cache[name], data, children)
}
相關文章
相關標籤/搜索