{
path: 'orderList',
name: 'orderList',
component: () => import('@/pages/order/orderList/index'),
meta: {
title: '订单列表',
keepAlive: true // 需要缓存
}
},
{
path: 'orderDetails',
name: 'orderDetails',
component: () => import('@/pages/order/orderList/orderDetails'),
meta: {title: '订单详情'}
},
<div>
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
// 这种有个弊端就是当前缓存的页面,下次进入是重新进入了,但是再需要返回到缓存的页面时,会是第一次缓存的信息,这样就不行了
beforeRouteLeave(to, from, next) {
// 当要去的页面不是orderDetails的时候,页面就不需要被缓存
to.name === 'orderDetails' ? from.meta.keepAlive = true : from.meta.keepAlive = false
next();
}
强制移除缓存
首先打印this.$vnode.parent 查看层级
再路由即将离开的时候强制移除
beforeRouteLeave(to, from, next) {
console.log('to==',to)
console.log('from==',from)
console.log('this.$vnode.key ==', this.$vnode)
// 强制移除的时候这句代码就不需要了
// to.name === 'vehicleLicense' ? from.meta.keepAlive = true : from.meta.keepAlive = false
if(to.name !== 'vehicleLicense' && this.$vnode.parent && this.$vnode.parent.parent.componentInstance.cache) {
let tag = this.$vnode.parent.tag // 当前关闭的组件名
let cache = this.$vnode.parent.parent.componentInstance.cache // 缓存的组件
let keys = this.$vnode.parent.parent.componentInstance.keys // 缓存的组件名
for(let index in keys){
if(cache[keys[index]].tag == tag){
delete cache[keys[index]]
keys.splice(index, 1)
}
}
<meta charset="utf-8">
<meta charset="utf-8">