1:路由配置文件设置
{
path: '/MenuM',
component: Layout,
redirect: '/MenuM',
children: [
{
path: 'MenuM',
name: 'MenuM',
component: () => import('@/views/MenuM'),
meta: { title: '主界面', icon: 'table', keepAlive: true }
}
]
},
2.标注需要缓存的组件,用包裹
这一步需要注意了,有的是在APP.VUE改,有的要看所在组件里改哦~~,比如上面的component: Layout,
那我们需要修改的文件就不是app.vue了,需要修改对应文件才行,
要不然就会无法缓存页面数据,出现问题
srclayoutcomponentsAppMain.vue
<template>
<section class="app-main">
<div class="app-main-top">
<transition name="fade-transform" mode="out-in">
<div>
<keep-alive>
<router-view v-if="$route.meta.keepAlive" :key="key"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" :key="key"></router-view>
<!-- <router-view :key="key" /> -->
</div>
</transition>
</div>
</section>
</template>
<script>
export default {
name: 'AppMain',
computed: {
key() {
return this.$route.path
}
}
}
</script>
<style lang="less" scoped>
.app-main {
/*50 = navbar */
min-height: calc(100vh - 50px);
100%;
position: relative;
overflow: hidden;
// background-image: url(~@/assets/image/bg01.jpg);
.app-main-top {
padding-top: 5px;
padding-bottom: 5px;
// background: rgba(255, 255, 255, 0.9);
background: rgba(255, 255, 255, 1); // 修改背景
min-height: calc(100vh - 50px);
}
}
.fixed-header + .app-main {
padding-top: 50px;
}
</style>
<style lang="scss">
// fix css style bug in open el-dialog
.el-popup-parent--hidden {
.fixed-header {
padding-right: 15px;
}
}
</style>
在router中设置需要缓存的组件
页面第一次进入,钩子的触发顺序created-> mounted-> activated,退出时触发deactivated。当再次进入(前进或者后退)时,只触发activated
可以动态控制是否缓存组件,代码如下:
beforeRouteLeave(to, from, next) {
// 设置下一个路由的 meta
to.meta.keepAlive = false; // 不缓存,即刷新
next();
}
参考来源
https://www.jianshu.com/p/eeda81293826
https://zhuanlan.zhihu.com/p/48628352