zoukankan      html  css  js  c++  java
  • Vue Keep-alive 原理

    Keep-alive 是 Vue 的一个内置组件,会缓存不活动的组件实例,防止重复渲染DOM。

     

    一、原理

      Vue 的缓存机制并不是直接存储 DOM 结构,而是将 DOM 节点抽象成了一个个 VNode节点

      因此,Vue 的 keep-alive 缓存也是基于 VNode节点 而不是直接存储 DOM 节点。

    二、参数

      Keep-alive 组件提供了 includeexclude 两个属性,允许组件有条件的进行缓存。 

      include: 字符串或正则表达式。只有匹配的组件会被缓存。

      exclude: 字符串或正则表达式。任何匹配的组件都不会被缓存。

    三、生命钩子函数(如果不使用 keep-alive,生命钩子函数不存在)

      Keep-alive 组件提供了两个生命钩子函数,分别是 activated 和 deactivated

      activated :当页面存在缓存的时候执行该函数。

      deactivated :在页面结束时触发该方法,可清除掉滚动方法等缓存。

    四、组件代码

      

    type VNodeCache = { [key: string]: ?VNode };
    
    const patternTypes: Array<Function> = [String, RegExp]
    
    /* 获取组件名称 */
    function getComponentName (opts: ?VNodeComponentOptions): ?string {
      return opts && (opts.Ctor.options.name || opts.tag)
    }
    
    /* 检测name是否匹配 */
    function matches (pattern: string | RegExp, name: string): boolean {
      if (typeof pattern === 'string') {
        /* 字符串情况,如a,b,c */
        return pattern.split(',').indexOf(name) > -1
      } else if (isRegExp(pattern)) {
        /* 正则 */
        return pattern.test(name)
      }
      /* istanbul ignore next */
      return false
    }
    
    /* 修正cache */
    function pruneCache (cache: VNodeCache, current: VNode, filter: Function) {
      for (const key in cache) {
        /* 取出cache中的vnode */
        const cachedNode: ?VNode = cache[key]
        if (cachedNode) {
          const name: ?string = getComponentName(cachedNode.componentOptions)
          /* name不符合filter条件的,同时不是目前渲染的vnode时,销毁vnode对应的组件实例(Vue实例),并从cache中移除 */
          if (name && !filter(name)) {
            if (cachedNode !== current) {
              pruneCacheEntry(cachedNode)
            }
            cache[key] = null
          }
        }
      }
    }
    
    /* 销毁vnode对应的组件实例(Vue实例) */
    function pruneCacheEntry (vnode: ?VNode) {
      if (vnode) {
        vnode.componentInstance.$destroy()
      }
    }
    
    /* keep-alive组件 */
    export default {
      name: 'keep-alive',
      /* 抽象组件 */
      abstract: true,
    
      props: {
        include: patternTypes,
        exclude: patternTypes
      },
    
      created () {
        /* 缓存对象 */
        this.cache = Object.create(null)
      },
    
      /* destroyed钩子中销毁所有cache中的组件实例 */
      destroyed () {
        for (const key in this.cache) {
          pruneCacheEntry(this.cache[key])
        }
      },
    
      watch: {
        /* 监视include以及exclude,在被修改的时候对cache进行修正 */
        include (val: string | RegExp) {
          pruneCache(this.cache, this._vnode, name => matches(val, name))
        },
        exclude (val: string | RegExp) {
          pruneCache(this.cache, this._vnode, name => !matches(val, name))
        }
      },
    
      render () {
        /* 得到slot插槽中的第一个组件 */
        const vnode: VNode = getFirstComponentChild(this.$slots.default)
    
        const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
        if (componentOptions) {
          // check pattern
          /* 获取组件名称,优先获取组件的name字段,否则是组件的tag */
          const name: ?string = getComponentName(componentOptions)
          /* name不在inlcude中或者在exlude中则直接返回vnode(没有取缓存) */
          if (name && (
            (this.include && !matches(this.include, name)) ||
            (this.exclude && matches(this.exclude, name))
          )) {
            return vnode
          }
          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
          /* 如果已经做过缓存了则直接从缓存中获取组件实例给vnode,还未缓存过则进行缓存 */
          if (this.cache[key]) {
            vnode.componentInstance = this.cache[key].componentInstance
          } else {
            this.cache[key] = vnode
          }
          /* keepAlive标记位 */
          vnode.data.keepAlive = true
        }
        return vnode
      }
    }
    View Code

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

    随笔整理自
       https://segmentfault.com/q/1010000011537852
      https://segmentfault.com/a/1190000011978825
    感谢博主分享!
  • 相关阅读:
    Google Map API使用详解(三)——Google Map基本常识(上)
    Google Map API使用详解(十)——使用JavaScript创建地图详解(上)
    sethc.exe
    taobao_java
    "void __cdecl operator delete[](void *)" (??_V@YAXPAX@Z) 已经在 LIBCMTD.lib(delete2.obj) 中定义 错误
    some Content
    变参 C++ 转帖
    阅读大型程序你得到什么
    一些模块
    a common jsp
  • 原文地址:https://www.cnblogs.com/gaosirs/p/10601463.html
Copyright © 2011-2022 走看看