第一步 在app中设置需要缓存的div
//缓存的页面
//不缓存的页面
第二步 在路由router.js中设置.vue页面是否需要缓存
{
path: '/',
name: 'HomePage',
component: HomePage,
meta: {
keepAlive: false, //此组件不需要被缓存
isBack: false, //用于判断上一个页面是哪个
}
},
{
path: '/insure',
name: 'Insure',
component: insure,
meta: {
keepAlive: true, //此组件需要被缓存
isBack:false, //用于判断上一个页面是哪个
}
},
{
path: '/confirm',
name: 'confirm',
component: confirm,
meta: {
keepAlive: false, //此组件不需要被缓存
isBack:false, //用于判断上一个页面是哪个
}
}
第三步
beforeRouteEnter(to, from, next) {
if (from.name == 'confirm') {
to.meta.isBack = true;
}
next();
}
第四步
当引入keep-alive的时候,页面第一次进入,钩子的触发顺序created-> mounted-> activated,退出时触发deactivated。
当再次进入(前进或者后退)时,只触发activated。
第五步
默认执行这个方法
activated() {
if (!this.$route.meta.isBack) { //true执行
// 如果isBack是false,表明需要获取新数据,否则就不再请求,直接使用缓存的数据
//清空表单
}
// 恢复成默认的false,避免isBack一直是true,导致下次无法获取数据
this.$route.meta.isBack = false;
}