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