所有页面都需要缓存时,直接使用keep-alive组件即可
<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>
<template>
<keep-alive :include="keepAlive">
<router-view></router-view>
</keep-alive>
</template>
<script>
export default {
name: 'Layout',
data() {
return {
keepAlive: ['componentA', 'componentB']
}
}
}
</script>
举例:从列表页进入详情页再回到列表页时,列表需要缓存;从其他页面进入列表页时,列表页不需要缓存
实现思路:
export default {
path: '/list',
component: () => import('../list.vue'),
meta: {
keepAlive: true,
componentName: 'List',
fromPath: ['/detail']
}
}
<template>
<keep-alive :include="keepAlive">
<router-view></router-view>
</keep-alive>
</template>
<script>
export default {
name: 'Layout',
data() {
return {
// 需要缓存的组件名称
keepAlive: []
}
},
beforeRouteUupdate(to, from, next) {
const { keepAlive, fromPath, componentName } = to.meta;
if (keepAlive) {
// 如果不是从详情页跳转到列表页,就清除列表页的缓存
if (Array.isArray(fromPath) && fromPath.every(item => item != from.path)) {
this.keepAlive = this.keepAlive.filter(item => item != componentName);
}
setTimeout(() => this.checkRouteKeep(to), 100);
}
next();
},
created() {
this.checkRouteKeep(this.$route);
},
methods: {
checkRouteKeep(route) {
const { keepAlive, componentName } = route.meta;
if (keepAlive && this.keepAlive.every(item => item != componentName)) {
this.keepAlive.push(componentName);
}
}
}
}
</script>