keep-alive基本用法以及底层源码分析

1,084 阅读4分钟

一、keep-alive基本

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

作用: 在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性

Props

  • include -字符串或正则表达式。只有名称匹配的组件会被缓存。
  • exclude -字符串或正则表达式。任何名称匹配的组件都不会被缓存。优先级大于include
  • max -数字。最多可以缓存多少组件实例。超出上限使用LRU的策略置换缓存数据。

LRU.png

hush.png

hushLink.png

生命周期函数

  • activated
  • deactivated

当组件在 <keep-alive> 内被切换,它的 activateddeactivated 这两个生命周期钩子函数将会被对应执行。且将会在 <keep-alive> 树内的所有嵌套组件中触发。

原理: 在 created 函数调用时将需要缓存的 VNode 节点保存在 this.cache 中/在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染。

  • VNode -虚拟DOM,其实就是一个JS对象
<template>
  <div id="app">
    // 1. 缓存 name为a的组件
    <keep-alive include="a">
      <router-view/>
    </keep-alive>

    // 2. 缓存 name为a或者b的组件,结合动态组件使用
    <keep-alive include="a,b">
      <router-view/>
    </keep-alive>

    // 3. 使用正则表达式,需要使用v-bind
    <keep-alive :include='/a|b/'>
      <router-view/>
    </keep-alive>

    // 4. 动态判断
    <keep-alive :include="componentsName">
      <router-view/>
    </keep-alive>

    // 5. 不缓存name 为 a 的组件
    <keep-alive exclude="a">
      <router-view/>
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

二、keep-alive扩展使用场景

1.缓存所有页面

在App.vue里面

<template>
  <div id="app">
    <keep-alive>
      <route-view />
    </keep-alive>
  </div>
</template>

2.根据条件缓存

第一章节基本使用方法↑

3.结合Router,缓存部分页面

在router目录下index.js内

export default new Router({
  mode: 'history',
  routes: [
    {
      path:'/',
      name:'home',
      component: Home,
      redirect: 'goods',
      children: [
        {
          path: 'goods',
          name: 'goods',
          component: Godds,
          meta: {
            keepAlive: false // 不需要缓存
          }
        },
        {
          path: 'seller',
          name: 'seller',
          component: Seller,
          meta: {
            keepAlive: true // 需要缓存
          }
        },
      ]
    }
  ]
})

在App.vue内

<template>
  <div id="app">
    <keep-alive>
      <route-view v-if="$route.meta.keepAlive"></route-view>
    </keep-alive>
      <route-view v-if="!$route.meta.keepAlive"></route-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

三、源码分析

源码路径:src/core/components/keep-alive.js keep-alive的内部工具函数:

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

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

// 01.获取组件名 参数:opts:组件配置
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}

// 02.匹配函数 参数:pattern:模式, name:组件名
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)
  }
  return false
}

// 03.删减缓存入口函数 参数:keepAliveInstance:当前keepAlive实例 filter:过滤方法
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)
      }
    }
  }
}

// 04.删减缓存处理函数, 缓存组件实例调用destroy
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() // 执行组件的destroy钩子函数
  }
  cache[key] = null
  remove(keys, key)
}

对外暴露的对象:

const patternTypes: Array<Function> = [String, RegExp, Array]

export default {
  name: 'keep-alive',
  abstract: true, // 抽象组件(该虚拟dom是否渲染真实dom)

  props: {
    include: patternTypes, // 缓存白名单
    exclude: patternTypes, // 缓存黑名单
    max: [String, Number] // 缓存组件阈值
  },

  created () {
    this.cache = Object.create(null) // 缓存虚拟dom
    this.keys = [] // 缓存虚拟dom的键值
  },

  destroyed () {
    // 销毁时清空所有缓存,不仅仅是将cache设置为空,删除缓存的VNode还要对应组件实例的destory钩子函数
    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) { // 存在组件参数
      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
      // 定义组件的缓存key
      const key: ?string = vnode.key == null
        ? 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键数组中删除该key
        keys.push(key) // 调整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包裹着的第一个子组件对象及其组件名;
  • 第二步:根据设定的黑白名单(如果有)进行条件匹配,决定是否缓存。不匹配,直接返回组件实例(VNode),否则执行第三步;
  • 第三步:根据组件ID和tag生成缓存Key,并在缓存对象中查找是否已缓存过该组件实例。如果存在,直接取出缓存值并更新该key在this.keys中的位置(更新key的位置是实现LRU置换策略的关键),否则执行第四步;
  • 第四步:在this.cache对象中存储该组件实例并保存key值,之后检查缓存的实例数量是否超过max设置值,超过则根据LRU置换策略删除最近最久未使用的实例(即是下标为0的那个key);
  • 第五步:最后并且很重要,将该组件实例的keepAlive属性值设置为true。

keep-alive-test.gif