Created
November 27, 2019 09:08
-
-
Save lingceng/c204bac2704d03db99932d5457e662e6 to your computer and use it in GitHub Desktop.
Function to clear vue keep-alive cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Vue2中为了多标签页管理后台,支持详情页多开,也是通过这种方式,但是 Vue3里面 cache和keys 放在setup里面了,是内部变量,无法通过外部访问,有解决方案吗?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
需要传递组件的实例,可以在 beforeRouterLeave 函数里获取。