业务需求:后台管理快捷菜单功能,当关闭某个路由时,keep-Alive缓存重置

我们可以通过控制路由里的meta.keepAlive状态来控制是否缓存,但是当我们多个详情页指向同一路由时,这个方法便不可行,因为一旦控制了组件的keepAlive状态,我们所有指向同一组件都会受到影响,显然不符合我们的需求。
解决方法
<keep-alive>
<router-view ref="keepAlive" :key="$route.fullPath"></router-view>
</keep-alive>
// 直接在keepAlive添加refs无法找到 我们可以把ref加在router-view上 通过$vnode.parent可以找到
let cacheList=this.$refs.keepAlive.$vnode.parent.componentInstance.cache
console一下cacheList

这样如果重置某个页面,我们便可以delete 某个key值就可以了
注意:如果当页面进入离开添加transition动画时,key值会变化。
解决方法:
如果路由切换时加了transition,这时候我们可以正则匹配__transition-***内容
let str = Object.keys(this.$refs.keepAlive.$vnode.parent.componentInstance.cache)
if (str.length != 0) {
const reg = /^__transition-(\d+)-\/.*$/;
const match = str[0].match(reg);
this.cacheCharacterNum = match ? match[1] : null;
}
打印cacheCharacterNum

这个时候我们在进行key对比删除就可以。
完整代码:
cacheCharacter() {
// 匹配路由地址跟动画之前的数字 以防每次刷新时key里面的数字不同 导致无法找到对应的key值
let str = Object.keys(this.$refs.keepAlive.$vnode.parent.componentInstance.cache)
if (str.length != 0) {
const reg = /^__transition-(\d+)-\/.*$/;
const match = str[0].match(reg);
this.cacheCharacterNum = match ? match[1] : null;
}
},
closeOther() {
// 删除keepAlive缓存数据
this.cacheCharacter()
let fullPath =`__transition-${this.cacheCharacterNum}-${_this.$route.fullPath}`
let cacheList = this.$refs.keepAlive.$vnode.parent.componentInstance.cache
for (const key of Object.keys(cacheList)) {
if (key !== fullPath) {
delete this.$refs.keepAlive.$vnode.parent.componentInstance.cache[key]
}
}
},
文章讲述了在Vue.js的后台管理中,如何处理路由的keep-alive缓存问题。当多个详情页指向同一路由时,通过路由的meta.keepAlive状态控制缓存不再适用。作者提出了一种解决方案,利用$refs和组件的key属性来动态管理缓存,特别是在有transition动画的情况下,通过正则匹配来处理key的变化,从而实现特定页面缓存的删除。

3528

被折叠的 条评论
为什么被折叠?



