原文: https://juejin.cn/post/6930915968655261703
原文有删改

Vue2.X 源码(keep-alive):

缓存的是整个 VNode

  1. /* @flow */
  2. import { isRegExp, remove } from 'shared/util'
  3. import { getFirstComponentChild } from 'core/vdom/helpers/index'
  4. type CacheEntry = {
  5. name: ?string;
  6. tag: ?string;
  7. componentInstance: Component;
  8. };
  9. type CacheEntryMap = { [key: string]: ?CacheEntry };
  10. function getComponentName (opts: ?VNodeComponentOptions): ?string {
  11. return opts && (opts.Ctor.options.name || opts.tag)
  12. }
  13. function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
  14. if (Array.isArray(pattern)) {
  15. return pattern.indexOf(name) > -1
  16. } else if (typeof pattern === 'string') {
  17. return pattern.split(',').indexOf(name) > -1
  18. } else if (isRegExp(pattern)) {
  19. return pattern.test(name)
  20. }
  21. /* istanbul ignore next */
  22. return false
  23. }
  24. function pruneCache (keepAliveInstance: any, filter: Function) {
  25. const { cache, keys, _vnode } = keepAliveInstance
  26. for (const key in cache) {
  27. const entry: ?CacheEntry = cache[key]
  28. if (entry) {
  29. const name: ?string = entry.name
  30. if (name && !filter(name)) {
  31. pruneCacheEntry(cache, key, keys, _vnode)
  32. }
  33. }
  34. }
  35. }
  36. function pruneCacheEntry (
  37. cache: CacheEntryMap,
  38. key: string,
  39. keys: Array<string>,
  40. current?: VNode
  41. ) {
  42. const entry: ?CacheEntry = cache[key]
  43. if (entry && (!current || entry.tag !== current.tag)) {
  44. entry.componentInstance.$destroy()
  45. }
  46. cache[key] = null
  47. remove(keys, key)
  48. }
  49. const patternTypes: Array<Function> = [String, RegExp, Array]
  50. export default {
  51. name: 'keep-alive',
  52. abstract: true,
  53. props: {
  54. include: patternTypes,
  55. exclude: patternTypes,
  56. max: [String, Number]
  57. },
  58. methods: {
  59. cacheVNode() {
  60. const { cache, keys, vnodeToCache, keyToCache } = this
  61. if (vnodeToCache) {
  62. const { tag, componentInstance, componentOptions } = vnodeToCache
  63. cache[keyToCache] = {
  64. name: getComponentName(componentOptions),
  65. tag,
  66. componentInstance,
  67. }
  68. keys.push(keyToCache)
  69. // prune oldest entry
  70. if (this.max && keys.length > parseInt(this.max)) {
  71. pruneCacheEntry(cache, keys[0], keys, this._vnode)
  72. }
  73. this.vnodeToCache = null
  74. }
  75. }
  76. },
  77. created () {
  78. this.cache = Object.create(null)
  79. this.keys = []
  80. },
  81. destroyed () {
  82. for (const key in this.cache) {
  83. pruneCacheEntry(this.cache, key, this.keys)
  84. }
  85. },
  86. mounted () {
  87. this.cacheVNode()
  88. this.$watch('include', val => {
  89. pruneCache(this, name => matches(val, name))
  90. })
  91. this.$watch('exclude', val => {
  92. pruneCache(this, name => !matches(val, name))
  93. })
  94. },
  95. updated () {
  96. this.cacheVNode()
  97. },
  98. render () {
  99. const slot = this.$slots.default
  100. const vnode: VNode = getFirstComponentChild(slot)
  101. const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
  102. if (componentOptions) {
  103. // check pattern
  104. const name: ?string = getComponentName(componentOptions)
  105. const { include, exclude } = this
  106. if (
  107. // not included
  108. (include && (!name || !matches(include, name))) ||
  109. // excluded
  110. (exclude && name && matches(exclude, name))
  111. ) {
  112. return vnode
  113. }
  114. const { cache, keys } = this
  115. const key: ?string = vnode.key == null
  116. // same constructor may get registered as different local components
  117. // so cid alone is not enough (#3269)
  118. ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
  119. : vnode.key
  120. if (cache[key]) {
  121. vnode.componentInstance = cache[key].componentInstance
  122. // make current key freshest
  123. remove(keys, key)
  124. keys.push(key)
  125. } else {
  126. // delay setting the cache until update
  127. this.vnodeToCache = vnode
  128. this.keyToCache = key
  129. }
  130. vnode.data.keepAlive = true
  131. }
  132. return vnode || (slot && slot[0])
  133. }
  134. }

关于 keep-alive

keep-alive 是一个抽象组件,不会和子组件建立父子关系,也不会作为节点渲染到页面上。
关于抽象组件 Vue 的文档没有提这个概念,它有一个属性 abstract 为 true,在抽象组件的生命周期过程中,我们可以对包裹的子组件监听的事件进行拦截,也可以对子组件进行 Dom 操作,从而可以对我们需要的功能进行封装,而不需要关心子组件的具体实现。除了kepp-alive还有等。

作用

  • 能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。
  • 避免反复渲染影响页面性能,同时也可以很大程度上减少接口请求,减小服务器压力。
  • 能够进行路由缓存和组件缓存。

    Activated

    keep-alive 的模式下多了 activated 这个生命周期函数, keep-alive 的声明周期执行:

  • 页面第一次进入,钩子的触发顺序

created-> mounted-> activated,退出时触发 deactivated 当再次进入(前进或者后退)时,只触发 activated。

  • 事件挂载的方法等,只执行一次的放在 mounted 中;组件每次进去执行的方法放在 activated 中。

    keep-alive解析

    源码文件位置: source-code\vue\src\core\components\keep-alive.js

    渲染

    keep-alive 是由 render 函数决定渲染结果,在开头会获取插槽内的子元素,调用 getFirstComponentChild 获取到第一个子元素的 VNode。
    1. const slot = this.$slots.default
    2. const vnode: VNode = getFirstComponentChild(slot)
    接着判断当前组件是否符合缓存条件,组件名与 include 不匹配或与 exclude 匹配都会直接退出并返回 VNode,不走缓存机制。
    1. // check pattern
    2. const name: ?string = getComponentName(componentOptions)
    3. const { include, exclude } = this
    4. if (
    5. // not included
    6. (include && (!name || !matches(include, name))) ||
    7. // excluded
    8. (exclude && name && matches(exclude, name))
    9. ) {
    10. return vnode
    11. }
    匹配条件通过会进入缓存机制的逻辑,如果命中缓存,从 cache 中获取缓存的实例设置到当前的组件上,并调整 key 的位置将其放到最后(LRU 策略)。 如果没命中缓存,将当前 VNode 缓存起来,并加入当前组件的 key。如果缓存组件的数量超出 max 的值,即缓存空间不足,则调用 pruneCacheEntry 将最旧的组件从缓存中删除,即 keys[0] 的组件。之后将组件的 keepAlive 标记为 true,表示它是被缓存的组件。

    LRU 缓存策略:从内存中找出最久未使用的数据置换新的数据。 算法根据数据的历史访问记录来进行淘汰数据,其核心思想是:如果数据最近被访问过,那么将来被访问的几率也更高。

  1. const { cache, keys } = this
  2. const key: ?string = vnode.key == null
  3. // same constructor may get registered as different local components
  4. // so cid alone is not enough (#3269)
  5. ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
  6. : vnode.key
  7. if (cache[key]) {
  8. vnode.componentInstance = cache[key].componentInstance
  9. // make current key freshest
  10. remove(keys, key)
  11. keys.push(key)
  12. } else {
  13. cache[key] = vnode
  14. keys.push(key)
  15. // prune oldest entry
  16. if (this.max && keys.length > parseInt(this.max)) {
  17. pruneCacheEntry(cache, keys[0], keys, this._vnode)
  18. }
  19. }

pruneCacheEntry 负责将组件从缓存中删除,它会调用组件 $destroy 方法销毁组件实例,缓存组件置空,并移除对应的 key。

  1. function pruneCacheEntry (
  2. cache: CacheEntryMap,
  3. key: string,
  4. keys: Array<string>,
  5. current?: VNode
  6. ) {
  7. const entry: ?CacheEntry = cache[key]
  8. if (entry && (!current || entry.tag !== current.tag)) {
  9. entry.componentInstance.$destroy()
  10. }
  11. cache[key] = null
  12. remove(keys, key)
  13. }
  14. export default {
  15. name: 'keep-alive',
  16. abstract: true,
  17. // ...
  18. destroyed () {
  19. for (const key in this.cache) {
  20. pruneCacheEntry(this.cache, key, this.keys)
  21. }
  22. },
  23. render(){}
  24. }

👉渲染总结

  1. 通过 getFirstComponentChild 获取第一个子组件,获取该组件的 name;
  2. 通过 include 与 exclude 属性进行匹配,判断当前组件是否要被缓存,如果匹配成功;
  3. 命中缓存则直接获取,同时更新 key 的位置;
  4. 不命中缓存则设置进缓存,同时检查缓存的实例数量是否超过 max, 超过则根据 LRU 策略删除最近最久未使用;
  5. 如果在中途有对 include 和 exclude 进行修改,通过 watch 来监听 include 和 exclude,在其改变时调用 pruneCache 以修改 cache 缓存中的缓存数据。

基于 keep-alive 缓存实现方案

方案一:整个页面缓存

一般采用在 router 的 meta 属性里增加一个 keepAlive 字段,然后在父组件或者根组件中,根据 keepAlive 字段的状态使用 keep-alive 标签,实现对路由的缓存:

  1. <keep-alive>
  2. <router-view v-if="$route.meta.keepAlive" />
  3. </keep-alive>
  4. <router-view v-if="!$route.meta.keepAlive" />

方案二:动态组件缓存

使用 vuex 配合 exclude 和 include,通过 include 和 exclude 决定那些组件进行缓存。注意这里说的是组件,并且 cachedView 数组存放的是组件的名字,如下:

  1. <keep-alive :include="$store.state.keepAlive.cachedView">
  2. <router-view></router-view>
  3. </keep-alive>

场景分析

在 SPA 应用中用户希望在 Tab 多个页面来回切换的时候,不要丢失查询的结果,关闭后清除缓存。
如下图: keep-alive 实现原理探究 - 图1
期望是用户在切换 Tab 时 页面时缓存的,当用户关闭 Tab ,重新从左侧菜单打开时是不缓存。

路由缓存方案

这样是持久缓存了整个页面,问题也就出现当用户通过 Tab 关闭页面然后从左侧打开菜单时是缓存的页面,这个不符合日常使用习惯,所以为了解决数据新鲜度的问题可以在 activated 触发查询请求就能保证数据的新鲜度。

  1. activated(){
  2. this.getData()
  3. }

但是使用后发现由于你切换 Tab 时每次都会请求数据,但是如果项目的数据量有很大频繁请求会给后端造成很大压力 。

动态组件缓存方案

版本一需要频繁拉去数据导致此方案已不合适只能动态缓存组件方案。

  1. <keep-alive :include="cachedViews">
  2. <router-view :key="key"></router-view>
  3. </keep-alive>

其中 cachedViews 是通过监听路由动态增加删除维护要缓存的组件名称(所以组件名称不要重复)数组:

  1. const state = {
  2. cachedViews: [],
  3. }
  4. const mutations = {
  5. ADD_VIEWS: (state, view) => {
  6. if (state.cachedViews.includes(view.name)) return
  7. state.cachedViews.push(view.name)
  8. },
  9. DEL_CACHED_VIEW: (state, view) => {
  10. const index = state.cachedViews.indexOf(view.name)
  11. index > -1 && state.cachedViews.splice(index, 1)
  12. },
  13. }
  14. const actions = {
  15. addCachedView({ commit }, view) {
  16. commit('ADD_VIEWS', view)
  17. },
  18. deleteCachedView({ commit }, view) {
  19. commit('DEL_CACHED_VIEW', view)
  20. },
  21. }
  22. export default {
  23. namespaced: true,
  24. state,
  25. mutations,
  26. actions,
  27. }

通过监听路由变化:

  1. watch: {
  2. '$route'(newRoute) {
  3. const { name } = newRoute
  4. const cacheRout = this.ISCACHE_MAP[name] || []
  5. cacheRout.map((item) => {
  6. store.dispatch('cached/addCachedView', { name: item })
  7. })
  8. },
  9. },
  10. // 当通过 Tab 关闭页面时清除组件名称:
  11. closeTag(newRoute) {
  12. const { name } = newRoute
  13. const cacheRout = this.ISCACHE_MAP[name] || []
  14. cacheRout.map((item) => {
  15. store.dispatch('cached/deleteCachedView', { name: item })
  16. })
  17. }

但是在遇到嵌套路由时在层级不同的 router-view 中切换 Tab 会出现缓存数据失效的问题,无法缓存组件,嵌套路由如下: keep-alive 实现原理探究 - 图2

如何解决?

  • 方案一:菜单嵌套,路由不嵌套

通过维护两套数据,一套嵌套给左侧菜单,一套扁平化后注册路由,改造后的路由: keep-alive 实现原理探究 - 图3

  • 方案二:修改 keep-alive 把 catch 对象到全局

通过上面 keep-alive 解析可以知道,keep-alive就是把通过 include 匹配的组件的 vnode,放到 keep-alive 组件的一个 cache 对象中,下次渲染时,如果能在这里面找到,就直接渲染vnode。所以把这个 cache 对象,放到全局去(全局变量或者 vuex),这样我就可以不用缓存 ParnetView 也能缓存其指定的子组件了。

  1. import Vue from 'vue'
  2. const cache = {}
  3. const keys = []
  4. export const removeCacheByName = (name) => {/* 省略移除代码 */}
  5. export default Object.assign({}, Vue.options.components.KeepAlive, {
  6. name: 'NewKeepAlive',
  7. created() {
  8. this.cache = cache
  9. this.keys = keys
  10. },
  11. destroyed() {},
  12. })
  • 方案三:修改 keep-alive 根据路由 name 缓存

从上文可以知道 keep-alive 是从 cache 中获取缓存的实例设置到当前的组件上,key 是组件的名称,可以通过改造 getComponentName 方法,组件名称获取更改为路由名称使其缓存的映射关系只与 route name 值有关系。

  1. function getComponentName(opts) {
  2. return this.$route.name
  3. }

cache 缓存 key 也更改为路由名称。