vue的keep-alive

vue的<keep-alive>主要是对组件进行缓存,在跳转到其他页面再跳回来时组件还是一样的状态,避免组件重新渲染,它是一个抽象组件,不会渲染到页面。下面来看下应用

//index.js
export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
     
    },
    {
      path:'/test',
      name:"Test",
      component:Test
      
    }
  ]
})


//App.vue
<template>
  <div id="app">
    <img src="./assets/logo.png">
     <keep-alive include="Test" exclude="HelloWorld"> 
    <router-view/>
    </keep-alive> 
  </div>
</template>



//Test.vue
<template>
  <div>
      <input type="text">
      <router-link to="/">跳转</router-link>
  </div>
</template>

//HelloWorld.vue
<template>
  <div class="hello">
    
    <input type='text'>
    <router-link to='/test'>跳转</router-link>
    
  </div>
</template>

<keep-alive></keep-alive>有三个值,默认是所有组件都被缓存,exclude的值是不需要被缓存的组件的名称,include是需要被缓存的组件的名称.exclude的优先级要大于include,它还有两个周期函数activated和deactivated,分别是在缓存组件的mounted生命周期之后和跳转到其他页面时触发,除此之外,它还有一个max值,规定了最多可以缓存多少组件。看了下源码,大概的意思就是将include缓存的组件放在一个数组中,当数组的长度大于max值时,他会移除最新进入这个数组的组件,然后再把当前要缓存的组件插入到数组中,如果当前组件已经在数组中,则把它移至数组的末尾

function getComponentName (opts: ?VNodeComponentOptions): ?string {
  //获取组件的name值或tag值
  return opts && (opts.Ctor.options.name || opts.tag)
}

function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
 //比较当前组件的name值和include值
  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)
  }
  /* istanbul ignore next */
  return false
}

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

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()
  }
  cache[key] = null//清除缓存的组件
  remove(keys, key)
}

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

export default {
  name: 'keep-alive',
  abstract: true,

  props: {
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },

  created () {
    this.cache = Object.create(null)
    this.keys = []//创建缓存的组件数组
  },

  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 () {
    const slot = this.$slots.default
    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
      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
        // make current key freshest
        remove(keys, key)
        keys.push(key)//将移除的组件再插入到数组的末尾
      } else {//当前组件不在原来的数组中
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        //判断缓存组件数量是否大于max值
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值