背景:
A页面进入B页面,返回A后页面不刷新,保留数据。A页面进入C页面,返回A页面刷新
实现:
对A页面进行keepalive,进入C,清除缓存。
代码:
App.vue页面
<div id="app">
<KeepAlive>
<router-view v-if="$route.meta.KeepAlive"/>
</KeepAlive>
<router-view v-if="!$route.meta.KeepAlive"/>
</div>
route.js
{
path: "/A",
name:'A',
meta: {
KeepAlive:true
},
component: () =>
import ('../vue/A'),
},
A页面
beforeRouteLeave(to, from, next) {
console.log('---beforeRouteLeave')
if(to.name != 'B'){
// 清楚缓存
let Vnode = this.$vnode;
let parentVnode = Vnode && Vnode.parent;
if (parentVnode && parentVnode.componentInstance && parentVnode.componentInstance.cache) {
var key = Vnode.key == null ? Vnode.componentOptions.Ctor.cid + (Vnode.componentOptions.tag ? `::${Vnode.componentOptions.tag}` : '') : Vnode.key;
var cache = parentVnode.componentInstance.cache;
var keys = parentVnode.componentInstance.keys;
if (cache[key]) {
this.$destroy();
if (keys.length) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
cache[key] = null;
}
}
}
next()
},