Vue 全站缓存之 keep-alive

参考:

https://zhuanlan.zhihu.com/p/40628211

https://www.jianshu.com/p/9523bb439950

什么是页面缓存

用户的浏览行为应该是逐渐深入的,通俗得讲就是浏览页面在不断前进。

而且这些页面之间还是有互动性存在的,两种互动行为:

  • 一. 用户前进时,总是进入新的页面。(比如在合同列表页反复加载多次列表之后,进入其中一个合同详情,再返回时,应该仍停留之前里列表页同一个位置,而不是重新刷新列表页。)
  • 二. 用户后退时,需要能保留前一页数据并继续操作。(比如,记到账时需要选择合同,选择合同时可以新建合同,新建合同时填了一堆数据可以去选择客户,在选择客户时又去创建了客户,那么这一堆操作下来应该能够做到:创建完客户后继续新建合同,建完合同后继续记该合同的到账

keep-alive 是一种页面缓存组件

keep-alive是一个抽象组件:它自身不会渲染一个DOM元素,也不会出现在父组件链中;使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

vue 支持 keep-alive 组件,如果启用,页面内的所有数据都会被保留,所以,上文的互动行为二后退时保留前一页数据继续操作没有问题。

 

---------------------------------------------------------------------------------------------------------------------------------------

 

使用

vue页面要起名字

方式1:缓存所有页面

在vue.app页面中修改 使用keep-alive 组件

 

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

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

 

方式2:根据条件缓存页面

  1. 在 App.vue 里面

 

<template>
  <div id="app">
  	// 1. 将缓存 name 为 test 的组件
  	<keep-alive include='test'>
      <router-view/>
    </keep-alive>
	
	// 2. 将缓存 name 为 a 或者 b 的组件,结合动态组件使用
	<keep-alive include='a,b'>
  	  <router-view/>
	</keep-alive>
	
	// 3. 使用正则表达式 过滤需要缓存的界面name
	<keep-alive :include='/a|b/'>
  	  <router-view/>
	</keep-alive>	
	
	// 5.动态判断 写一个computed函数方法 过滤要缓存的界面name
	<keep-alive :include='includedComponents'>
  	  <router-view/>
	</keep-alive>
	
	// 5. 将不缓存 name 为 test 的组件
	<keep-alive exclude='test'>
  	  <router-view/>
	</keep-alive>
  </div>
</template>

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

方式3:结合Router,缓存部分页面 不通过界面名字

  1. 在 router 目录下的 index.js 文件里
    import Vue from 'vue'
    import Router from 'vue-router'
    const Home = resolve => require(['@/components/home/home'], resolve)
    const Goods = resolve => require(['@/components/home/goods'], resolve)
    const Ratings = resolve => require(['@/components/home/ratings'], resolve)
    const Seller = resolve => require(['@/components/home/seller'], resolve)
    
    Vue.use(Router)
    
    export default new Router({
      mode: 'history',
      routes: [
        {
          path: '/',
          name: 'home',
          component: Home,
          redirect: 'goods',
          children: [
            {
              path: 'goods',
              name: 'goods',
              component: Goods,
              meta: {
            	keepAlive: false // 不需要缓存
          	  }
            },
            {
              path: 'ratings',
              name: 'ratings',
              component: Ratings,
              meta: {
            	keepAlive: true  // 需要缓存
          	  }
            },
            {
              path: 'seller',
              name: 'seller',
              component: Seller,
              meta: {
            	keepAlive: true  // 需要缓存
          	  }
            }
          ]
        }
      ]
    })

     

  2. 在 App.vue 里面
    <template>
      <div id="app">
      	<keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App'
    }
    </script>
    

    最后,我们说说原理

     keep-alive.js的源码

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() {
    for (const key in this.cache) {
       // 删除所有的缓存
       pruneCacheEntry(this.cache, key, this.keys)
    }
  },
 mounted() {
   // 实时监听黑白名单的变动
   this.$watch('include', val => {
       pruneCache(this, name => matched(val, name))
   })
   this.$watch('exclude', val => {
       pruneCache(this, name => !matches(val, name))
   })
 },

 render() {
    // 先省略...
 }
}

可以看出,与我们定义组件的过程一样,先是设置组件名为keep-alive,其次定义了一个abstract属性,值为true。这个属性在vue的官方教程并未提及,却至关重要,后面的渲染过程会用到。props属性定义了keep-alive组件支持的全部参数。

keep-alive在它生命周期内定义了三个钩子函数:

  • created
    初始化两个对象分别缓存VNode(虚拟DOM)和VNode对应的键集合
  • destroyed
    删除this.cache中缓存的VNode实例。我们留意到,这不是简单地将this.cache置为null,而是遍历调用pruneCacheEntry函数删除。
// src/core/components/keep-alive.js
function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
 const cached = cache[key]
 if (cached && (!current || cached.tag !== current.tag)) {
    cached.componentInstance.$destroyed() // 执行组件的destroy钩子函数
 }
 cache[key] = null
 remove(keys, key)
}

删除缓存的VNode还要对应组件实例的destory钩子函数

  • mounted
    在mounted这个钩子中对include和exclude参数进行监听,然后实时地更新(删除)this.cache对象数据。pruneCache函数的核心也是去调用pruneCacheEntry


 

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

render

render () {
  const slot = this.$slots.defalut
  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
    // 定义组件的缓存key
    const key: ?string = vnode.key === null ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key
     if (cache[key]) { // 已经缓存过该组件
        vnode.componentInstance = cache[key].componentInstance
        remove(keys, key)
        keys.push(key) // 调整key排序
     } else {
        cache[key] = vnode //缓存组件对象
        keys.push(key)
        if (this.max && keys.length > parseInt(this.max)) {
          //超过缓存数限制,将第一个删除
          pruneCacheEntry(cahce, 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。Vue的渲染过程

Vue的渲染过程

Vue的渲染是从图中render阶段开始的,但keep-alive的渲染是在patch阶段,这是构建组件树(虚拟DOM树),并将VNode转换成真正DOM节点的过程。
简单描述从render到patch的过程
我们从最简单的new Vue开始:

import App from './App.vue'

new Vue({
    render: h => h(App)
}).$mount('#app')
  • Vue在渲染的时候先调用原型上的_render函数将组件对象转化成一个VNode实例;而_render是通过调用createElement和createEmptyVNode两个函数进行转化;
  • createElement的转化过程会根据不同的情形选择new VNode或者调用createComponent函数做VNode实例化;
  • 完成VNode实例化后,这时候Vue调用原型上的_update函数把VNode渲染成真实DOM,这个过程又是通过调用patch函数完成的(这就是patch阶段了)
    用一张图表达:


 

keep-alive包裹的组件是如何使用缓存的?

在patch阶段,会执行createComponent函数:

// src/core/vdom/patch.js
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
    let i = vnode.data
    if (isDef(i)) {
        const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
        if (isDef(i = i.hook) && isDef(i = i.init)) {
            i(vnode, false)
        }
        if (isDef(vnode.componentInstance)) {
            initComponent(vnode, insertedVnodeQueue)
            insert(parentElem, vnode.elem, refElem) // 将缓存的DOM(vnode.elem) 插入父元素中
            if (isTrue(isReactivated)) {
                reactivateComponent(vnode, insertedVnodeQueue, parentEle, refElm)
            }
            return true
        }
    }
}
  • 在首次加载被包裹组建时,由keep-alive.js中的render函数可知,vnode.componentInstance的值是undfined,keepAlive的值是true,因为keep-alive组件作为父组件,它的render函数会先于被包裹组件执行;那么只执行到i(vnode,false),后面的逻辑不执行;
  • 再次访问被包裹组件时,vnode.componentInstance的值就是已经缓存的组件实例,那么会执行insert(parentElm, vnode.elm, refElm)逻辑,这样就直接把上一次的DOM插入到父元素中。

五、不可忽视:钩子函数

5.1 只执行一次的钩子

一般的组件,每一次加载都会有完整的生命周期,即生命周期里面对于的钩子函数都会被触发,为什么被keep-alive包裹的组件却不是呢?
被缓存的组件实例会为其设置keepAlive= true,而在初始化组件钩子函数中:


(可参考我写的vue生命周期)

// src/core/vdom/create-component.js
const componentVNodeHooks = {
    init (vnode: VNodeWithData, hydrating: boolean): ?boolean{
        if (
         vnode.componentInstance &&       
         !vnode.componentInstance._isDestroyed &&
         vnode.data.keepAlive
        ) {
          // keep-alive components, treat as a patch
          const mountedNode:any = vnode
          componentVNodeHooks.prepatch(mountedNode, mountedNode)
        } else {
          const child = vnode.componentInstance = createComponentInstanceForVnode (vnode, activeInstance)
           
        }
    }
}

可以看出,当vnode.componentInstance和keepAlive同时为true时,不再进入$mount过程,那mounted之前的所有钩子函数(beforeCreate、created、mounted)都不再执行。

5.2 可重复的activated

在patch的阶段,最后会执行invokeInsertHook函数,而这个函数就是去调用组件实例(VNode)自身的insert钩子:

// src/core/vdom/patch.js
function invokeInsertHook (vnode, queue, initial) {
      if (isTrue(initial) && isDef(vnode.parent)) {
          vnode.parent.data,pendingInsert = queue
      } else {
         for(let i =0; i<queue.length; ++i) {
                queue[i].data.hook.insert(queue[i]) // 调用VNode自身的insert钩子函数
         }
      }
}
const componentVNodeHooks = {
      // init()
     insert (vnode: MountedComponentVNode) {
           const { context, componentInstance } = vnode
           if (!componentInstance._isMounted) {
                 componentInstance._isMounted = true
                 callHook(componentInstance, 'mounted')
           }
           if (vnode.data.keepAlive) {
                 if (context._isMounted) {
                     queueActivatedComponent(componentInstance)
                 } else {
                      activateChildComponent(componentInstance, true/* direct */)
                 }
          }
         // ...
     }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值