使用keep-alive组件对需要缓存的组件进行包裹
1.在app.vue中使用keep-alive组件对RouterView进行包裹
<keep-alive>
<RouterView v-if="$route.meta.keepAlive" />
</keep-alive>
<RouterView v-if="!$route.meta.keepAlive" />
2.在需要缓存的页面中配置路由元信息meta,将keepAlive的值设为true
{
path: '/home',
name: 'home',
component: () => import('../views/Home.vue'),
meta: {
keepAlive: true
}
},
3.在列表页通过组件内的路由守卫beforeRouteLeave(离开前)来判断当前页面即将跳转的页面是不是详情页,如果是,就将keepAlive值设为true,如果不是,设为false
防止其他页面返回列表页时数据不刷新
beforeRouteLeave(to,from,next){
if(["detail"].includes(to.name)){
from.meta.keepAlive = true;
}else{
from.meta.keepAlive = false;
}
next();
}