瞅瞅vue2.0 <keep-alive>

<keep-alive>作为一个内置组件,定义在src/core/components/keep-alive.js中:

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
    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 {
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

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

keep-alive是一个函数式组件,是通过执行内部的render函数来实现的。

1、首先组件接受三个属性:include、exclude和max,前两个可以传[String, RegExp、Array],max可以传[String, Number],include表示匹配到的可以缓存,exclude表示匹配到的不会被缓存,max表示缓存的大小,因为缓存对象是VNode,它也会持有DOM,因此会占用一定的内存。

2、在created里,声明了变量cache和keys,毫无疑问是用来缓存组件的。cache对象存放key和对应的组件,keys是一个数组存放所有需缓存的key。

3、destroyed钩子中,会遍历cache对象,执行pruneCacheEntry函数:

// pruneCacheEntry函数 
function pruneCacheEntry ( 
  cache: VNodeCache, 
  key: string, 
  keys: Array<string>, 
  current?: VNode 
) { 
 const cached = cache[key] /* 判断当前没有处于被渲染状态的组件,将其销毁*/ 
 if (cached && (!current || cached.tag !== current.tag)) { 
  cached.componentInstance.$destroy() 
 } 
 cache[key] = null
 remove(keys, key) 
}

4、mounted函数里对include和exclude进行观测,发生了变化,则执行pruneCache函数:

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

取每项的name与新缓存规则进行匹配,如果匹配不上,则表该组件已不需要被缓存,则剔除。

5、接下来就是重点render函数。

首先两行代码从函数名可以看出,先获取第一个子组件节点的vnode,keep-alive只会处理第一个子元素,这个在实际使用过程中是可以体会到的。

然后获取了节点的名称:

/* 优先获取组件的name字段,如果name不存在则获取组件的tag */ 
function getComponentName (opts: ?VNodeComponentOptions): ?string { 
  return opts && (opts.Ctor.options.name || opts.tag) 
}

接下来就把name拿去匹配一下not include和exclude,若不需要缓存,则直接返回vnode。否则就走缓存:

进缓存的逻辑大致比较简单,如果当前组件已命中缓存,则之间从缓存里面拿vnode组件实例,然后把当前key挪到数组最后一个;否则就加进缓存。最后还会看看有没有max的限制,超过限制还得删掉缓存第一个。

这里,为什么要调整命中的key的顺序,并且超长后要删掉第一个缓存组件呢?

因为应用的是一个缓存淘汰策略LRU( Least Recently Used)最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。因此命中缓存的被访问的key和新加的数据,都被视为未来访问几率高的数据,在这种策略下,但数据需要删除时,当然就是头部第一个缓存组件优先被删掉。

所以<keep-alive>包裹的组件和普通组件有什么区别呢?这里我们关注组件的首次渲染和缓存渲染。

这其中涉及到patch过程中的createComponent和reactivateComponent函数,总的来说就是keep-alive包裹的组件在首次渲染时会进入created、mounted这些生命周期,但是在再次渲染时,则不会了。如果想在再次渲染时做些什么,可以用Vue提供的activated钩子,自然也有相应的deactivated函数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值