1.app.vue文件
<template>
<div>
<!--需要缓存-->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<!--不需要缓存-->
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
2.router.js文件
{
path:'/loanmessage',
component:loanmessage,
name:'loanmessage',
meta: {
keepAlive: true, //代表需要缓存
isBack: false,
},
3.在需要缓存的页面加入如下代码
beforeRouteEnter(to, from, next) {
if (from.name == 'creditInformation' || from.name == 'cityList') {
to.meta.isBack = true;
}
next();
},
activated() {
this.getData()
this.$route.meta.isBack = false
this.isFirstEnter = false
},
注意事项
1.钩子函数执行顺序
- 不使用keep-alive
beforeRouteEnter --> created --> mounted --> destroyed
- 使用keep-alive
beforeRouteEnter --> created --> mounted --> activated --> deactivated
再次进入缓存的页面,只会触发beforeRouteEnter -->activated --> deactivated 。created和mounted不会再执行。
2. 为什么beforeRouteEnter钩子不执行
因为文档中说
路由组件指的是在定义router时component属性所指定的文件,普通组件、子组件等不属于路由组件,所以在他们里面调用这些路由钩子不生效
文章仅学习用,参考并转载自:
https://www.cnblogs.com/baifangzi/p/14481820.html
https://www.cnblogs.com/helloyong123/archive/2020/08/03/13427275.html