vue keep alive详解

基础

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

当组件在 <keep-alive> 内被切换,它的 activateddeactivated 这两个生命周期钩子函数将会被对应执行。

在 2.2.0 及其更高版本中,activateddeactivated 将会在 <keep-alive> 树内的所有嵌套组件中触发。

主要用于保留组件状态或避免重新渲染。

<!-- 基本 -->
<keep-alive>
  <component :is="view"></component>
</keep-alive>

<!-- 多个条件判断的子组件 -->
<keep-alive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b v-else></comp-b>
</keep-alive>

<!--`<transition>` 一起使用 -->
<transition>
  <keep-alive>
    <component :is="view"></component>
  </keep-alive>
</transition>

注意,<keep-alive> 是用在其一个直属的子组件被开关的情形。如果你在其中有 v-for 则不会工作。如果有上述的多个条件性的子元素,<keep-alive> 要求同时只有一个子元素被渲染。

include and exclude (2.1.0 新增)

include - 字符串,正则表达式或数组。只有名称匹配的组件会被缓存。
exclude - 字符串,正则表达式或数组。任何名称匹配的组件都不会被缓存。

includeexclude prop 允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:

<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

max (2.5.0 新增)

max - 数字。最多可以缓存多少组件实例。

扫描二维码关注公众号,回复: 13125140 查看本文章

一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉(LRU的策略置换缓存数据)。即max为1时,不缓存。

LRU:内存管理的一种页面置换算法,对于在内存中但又不用的数据块(内存块)叫做LRU,操作系统会根据哪些数据属于LRU而将其移出内存而腾出空间来加载另外的数据。

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

设计全站缓存

我们既希望填写一半进入下一页面时能保留填写的数据,我们又希望新进入的表单是一个全新的表单页。

换句话说,回到上一个页面时使用缓存,进入下一个页面时不使用缓存,

再换句话说,所有页面都用缓存,只在后退(回到上一页)时移除当前页缓存,这样下一次前进(进入当前页)时因为没有缓存就自然使用全新页面,

也就是说,只要实现后退(回到上一页)时移除当前页缓存这个功能,就可以了。

在路由中定义位置

这是一种缓存复用的思路,为了实现后退(回到上一页)时移除当前页缓存,因为想要实现动态确定用户的前进后退行为比较麻烦,所以,我们有个傻瓜式的方案:预测使用场景约定各路由页面的层级关系。

比如,在 routes 定义里,我们可以这么定义各路由页:

// 仅供参考,此处缺少路由组件定义
// router/index.js
routes: [
        {
    
       path: '/', redirect:'/yingshou', },
        {
    
       path: '/yingshou',                meta:{
    
    rank:1.5},},
        {
    
       path: '/contract_list',           meta:{
    
    rank:1.5},},
        {
    
       path: '/customer',                meta:{
    
    rank:1.5},},
        {
    
       path: '/wode',                    meta:{
    
    rank:1.5},},
        {
    
       path: '/yingfu',                  meta:{
    
    rank:1.5},},
        {
    
       path: '/yingfu/pact_list',        meta:{
    
    rank:2.5},},
        {
    
       path: '/yingfu/pact_detail',      meta:{
    
    rank:3.5},},
        {
    
       path: '/yingfu/expend_view',      meta:{
    
    rank:4.5},},
        {
    
       path: '/yingfu/jizhichu',         meta:{
    
    rank:5.5},},
        {
    
       path: '/yingfu/select_pact',      meta:{
    
    rank:6.5},},
        {
    
       path: '/yingfu/jiyingfu',         meta:{
    
    rank:7.5},},
    ]

核心的思路是,在定义路由时,在 meta 中定义一个 rank 字段来声明该路由的页面优先级, 比如 1.5 标识第 1 层如首页,2.5 表示第 2 层如商品列表页, 3.5标识第 3 层商品详情页,以此类推。

如果大家同在一层,也可以通过 1.4 和 1.5 这样小数位来约定先后层级。

总之,我们期望的是,从第1层进入第2层是前进,从第3层回到第2层是后退。

在路由跳转里动态判断移除缓存

使用Vue.mixin的方法拦截了路由离开事件,并在该拦截方法中实现后退时销毁页面缓存。

// main.js
Vue.mixin({
    
    
    beforeRouteLeave:function(to, from, next){
    
    
        if (from.meta.rank && to.meta.rank && from.meta.rank > to.meta.rank){
    
    
          //此处判断是如果返回上一层,你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
            if (this.$vnode && this.$vnode.data.keepAlive)
            {
    
    
                if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
                {
    
    
                    if (this.$vnode.componentOptions)
                    {
    
    
                        var key = this.$vnode.key == null
                                    ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${
      
      this.$vnode.componentOptions.tag}` : '')
                                    : this.$vnode.key;
                        var cache = this.$vnode.parent.componentInstance.cache;
                        var keys  = this.$vnode.parent.componentInstance.keys;
                        if (cache[key])
                        {
    
    
                            if (keys.length) {
    
    
                                var index = keys.indexOf(key);
                                if (index > -1) {
    
    
                                    keys.splice(index, 1);
                                }
                            }
                            delete cache[key];
                        }
                    }
                }
            }
            this.$destroy();
        }
        next();
    },
});

缓存给页面复用带来的问题

即使是路由页面复用了缓存,也只是复用了缓存的组件和数据,在实际场景中,从列表 A 进入详情 B 再进入列表 C ,请问 列表 C 和列表 A 是同一个路由页,但他们的数据会一样吗?应该一样吗?

看起来,我们得到了一个新结论,缓存页的数据也不可靠啊。

缓存的组件被复用时会触发 activated 事件,非缓存组件则会在创建时触发 created mounted 等一大堆事件,而同一个页面列表 A 进列表 B,因为 url 参数不同,也会触发beforeRouteUpdate事件。

我们在捕捉到页面载入的事件后去拉取数据更新页面。

这里提供一个笨办法,事件该捕捉咱还是要捕捉,只是这是否去做拉取数据这个动作,咱可以有待商榷。

在需要的路由页统一注册一个方法,就叫pageenter吧,不管从啥情况进来的,咱都去触发这个方法。

// list.vue
methods:{
    
    
    pageenter:function(){
    
    
       //此处拉取数据
       //this.$http.get(....)
    },
}

在main.js里,可以用Vue.mixin拦截上文提到的三种事件,来触发 pageenter 方法。

// main.js
Vue.mixin({
    
    
	/*初始化组件时,触发pageenter方法*/
	created:function(){
    
    
	   if (this.pageenter){
    
    
	       this.pageenter();
	   }
	},
	/*激活当前组件时*/
	activated:function(){
    
    
	   if (this.pageenter){
    
    
	       this.pageenter();
	   }
	},
	/*在同一组件中,切换路由(参数变化)时*/
	beforeRouteUpdate:function(to, from, next){
    
    
	    if (this.pageenter){
    
    
	        this.$nextTick(()=>{
    
    
	            this.pageenter();
	        });
	    }
	    next();
	},
});

原理解析

源码剖析

keep-alive.js内部还定义了一些工具函数,我们按住不动,先看它对外暴露的对象

// src/core/components/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 => matches(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.$destroy() // 执行组件的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 
    // 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
        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渲染过程.png
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阶段了)

用一张图表达:
渲染过程.png

keep-alive组件的渲染

我们用过keep-alive都知道,它不会生成真正的DOM节点,这是怎么做到的?

// src/core/instance/lifecycle.js
export function initLifecycle (vm: Component) {
    
    
    const options = vm.$options
    // 找到第一个非abstract父组件实例
    let parent = options.parent
    if (parent && !options.abstract) {
    
    
        while (parent.$options.abstract && parent.$parent) {
    
    
              parent = parent.$parent
        }
        parent.$children.push(vm)
    }
    vm.$parent = parent
    // ...
}

Vue在初始化生命周期的时候,为组件实例建立父子关系会根据abstract属性决定是否忽略某个组件。在keep-alive中,设置了abstract:true,那Vue就会跳过该组件实例。

最后构建的组件树中就不会包含keep-alive组件,那么由组件树渲染成的DOM树自然也不会有keep-alive相关的节点了。

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(parentElm, vnode.elm, refElm) // 将缓存的DOM(vnode.elem) 插入父元素中
            if (isTrue(isReactivated)) {
    
    
                reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)
            }
            return true
        }
    }
}
  • 在首次加载被包裹组件时,由keep-alive.js中的render函数可知,vnode.componentInstance的值是undfined,keepAlive的值是true,因为keep-alive组件作为父组件,它的render函数会先于被包裹组件执行;那么只执行到i(vnode,false),后面的逻辑不执行;
  • 再次访问被包裹组件时,vnode.componentInstance的值就是已经缓存的组件实例,且keepAlive为true,那么会执行reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)逻辑,这样就直接把上一次的DOM插入到父元素中。

不可忽视:钩子函数

只执行一次的钩子

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

// 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)
          child.$mount(hydrating ? vnode.elm : undefined, hydrating)
        }
    }
}

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

可重复的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钩子函数
         }
      }
}

再看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 */)
                 }
          }
         // ...
     }
}

在这个钩子里面,调用了activateChildComponent函数递归地去执行所有子组件的activated钩子函数:

// src/core/instance/lifecycle.js
export function activateChildComponent (vm: Component, direct?: boolean) {
    
    
  if (direct) {
    
    
    vm._directInactive = false
    if (isInInactiveTree(vm)) {
    
    
      return
    }
  } else if (vm._directInactive) {
    
    
    return
  }
  if (vm._inactive || vm._inactive === null) {
    
    
    vm._inactive = false
    for (let i = 0; i < vm.$children.length; i++) {
    
    
      activateChildComponent(vm.$children[i])
    }
    callHook(vm, 'activated')
  }
}

相反地,deactivated钩子函数也是一样的原理,在组件实例(VNode)的destroy钩子函数中调用deactivateChildComponent函数。

猜你喜欢

转载自blog.csdn.net/weixin_44116302/article/details/113487660