使用<keep-alive />保存状态
1.在app.vue里使用keepalive
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
2.在需要保存状态的页面路由下写入keepAlive
{
path: '/index',
name: 'index',
component: index,
meta: {
keepAlive: true
}
},
3.在列表页通过路由守卫beforeRouteLeave,判断当前页面即将跳转的页面,如果是跳转详情页,就保持当前页面的keepAlive为true,来缓存列表页面,否则false,用来防止列表页返回其他页面后,再次访问列表页时数据不刷新的问题
beforeRouteLeave(to, from, next) {
//[].includes() 是es7写法,用来判断某个数组里是否包含有个元素,这里前边放详情页的名字,to.name是指即将跳转页面的name
if (["indexDetail"].includes(to.name)) {
from.meta.keepAlive = true;
} else {
from.meta.keepAlive = false;
}
next();
}
网友评论