Skip to content

Instantly share code, notes, and snippets.

@lingceng
Created November 27, 2019 09:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lingceng/c204bac2704d03db99932d5457e662e6 to your computer and use it in GitHub Desktop.
Save lingceng/c204bac2704d03db99932d5457e662e6 to your computer and use it in GitHub Desktop.
Function to clear vue keep-alive cache
function remove (arr, item) {
if (arr.length) {
let index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
function pruneCacheEntry (cache, key, keys, current) {
var cachedItem = cache[key];
if (cachedItem && (!current || cachedItem.tag !== current.tag)) {
cachedItem.componentInstance.$destroy();
}
cache[key] = null;
remove(keys, key);
}
// 清除keep-alive中某个组件的缓存,逻辑参考 keep-alive 的源码实现
// instance 参数是需要清除的组件的实例对象,这个组件需要是 keep-alive 的直接子组件
// https://github.com/vuejs/vue/issues/6509
export default function clearAliveCache(instance) {
let attributesRequired = instance.$vnode &&
instance.$vnode.data.keepAlive &&
instance.$vnode.parent &&
instance.$vnode.parent.componentInstance &&
instance.$vnode.parent.componentInstance.cache &&
instance.$vnode.componentOptions
if (!attributesRequired) {
return false
}
let tag = instance.$vnode.componentOptions.tag ? '::' + instance.$vnode.componentOptions.tag : ''
let key = !instance.$vnode.key ? instance.$vnode.componentOptions.Ctor.cid + tag : instance.$vnode.key
let { cache, keys, _vnode } = instance.$vnode.parent.componentInstance
pruneCacheEntry(cache, key, keys, _vnode)
}
@ijry
Copy link

ijry commented Nov 28, 2019

这个怎么使用啊

@lingceng
Copy link
Author

这个怎么使用啊

需要传递组件的实例,可以在 beforeRouterLeave 函数里获取。

  beforeRouteLeave (to, from, next) {
    store.commit('alive/pushRouterQuue', { router: from, instance: this })
    next()
  }

@FourLeafClover
Copy link

Vue2中为了多标签页管理后台,支持详情页多开,也是通过这种方式,但是 Vue3里面 cache和keys 放在setup里面了,是内部变量,无法通过外部访问,有解决方案吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment