keep-alive源码笔记二-删除keep-alive缓存

1. App.vue 中保存 keep-alive 的实例
--- html ---
<div id="app">
 <keep-alive ref="keepAlive">
   <router-view></router-view>
 </keep-alive>
 <router-link to="/">home</router-link>
 <router-link to="/about">about</router-link>
</div>
--- js ---
mounted() {
 // 这里要注意keep-alive在父组件中的位置,也可以通过匹配tag属性来获取keep-alive的实例
 // 也可绑定到vuex中
 window._keepAliveIns = this._vnode.children[0].componentInstance
 console.log(this._vnode.children[0].componentInstance, '_keepAliveIns ')
}

也可以通过匹配tag属性来获取keep-alive的实例
在这里插入图片描述

2. 在组件中删除缓存
--- component ---
<div>
  <button @click="del">del</button>
</div>
--- js ---
del() {
  // 删除所有缓存
  // window._keepAliveIns.cache = {}
  // window._keepAliveIns.keys.length = 0
  
  // 删除某个缓存
  // 获取当前组件的name,也可以指定其他组件的name
  const currKey = this._vnode.context.$options.name
  const cache = window._keepAliveIns.cache
  const targetEntry = Object.entries(cache).find(([key, value]) => {
    return value && (value.name == currKey )
  })
  if(targetEntry) {
    const keys = window._keepAliveIns.keys
    const delKey = targetEntry[0]
    this.pruneCacheEntry(cache, delKey, keys, this._vnode)
  }
},

// pruneCacheEntry,remove 是源码中删除缓存的方法
pruneCacheEntry (cache, key, keys, current) {
  const entry = cache[key]
  if (entry && (!current || entry.tag !== current.tag)) {
    entry.componentInstance.$destroy()
  }
  cache[key] = null
  this.remove(keys, key)
},
remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值