目录
一、app.vue文件中使用 <keep-alive>:
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
二、路由文件配置父路由的meta.keepAlive和子路由的meta.parent:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
import FATHER from '@V/father.vue';
import SON from '@V/son.vue';
const router = new Router({
routes: [
{
path: '/father',
name: 'father',
component: FATHER,
meta: {
keepAlive: true// 开启页面缓存
}
},
{
path: '/son',
name: 'son',
component: SON,
meta: {
keepAlive: false,
parent: "father"// 父路由的name
}
}
]
})
三、keepAlive.js混入文件:
export default {
data() {
return {
scrollDom: "",// 页面滚动ref名称(可选项,默认记录body层)
scrollTop: 0// 记录滚动高度
}
},
activated() {
// 默认设置body滚动高度, 若scrollDom指定元素, 则设置指定元素滚动高度
if(this.scrollDom) {
this.$refs[this.scrollDom].scrollTop = this.scrollTop;
} else {
document.body.scrollTop = this.scrollTop;
}
},
beforeRouteLeave(to, from, next) {
if(from.name === to.meta.parent) {
// 即将前往子路由页面: 默认保存body滚动高度, 若scrollDom指定元素, 则保存指定元素滚动高度
this.scrollTop = this.scrollDom ? this.$refs[this.scrollDom].scrollTop : document.body.scrollTop;
} else {
// 即将前往非子路由页面: 初始化变量 && 删除keepAlive缓存的页面
this.initKeepAlive();
}
next();
},
methods: {
initKeepAlive() {
try {
// 初始化变量
this.scrollDom = "";
this.scrollTop = 0;
// 删除keepAlive缓存的页面
let cid = this.$vnode.key ? this.$vnode.key : this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : "");
let aliveCids = this.$vnode.parent.componentInstance.keys;
let aliveHistory = this.$vnode.parent.componentInstance.cache;
let i = aliveCids.indexOf(cid);
if(i > -1) aliveCids.splice(i, 1);
delete(aliveHistory[cid]);
} catch(e) {
console.error("initKeepAlive失败: ", e);
}
}
}
}
四、父页面混入:
<template>
<div ref="father" class="father">
</div>
</template>
<script>
import keepAlive from "@CF/keepAlive.js";
export default {
mixins: [keepAlive],
mounted() {
this.scrollDom = "father";// 指定捕捉ref="father"的滚动高度
}
}
</script>
<style lang="less" scoped>
</style>
以上,现在从父页面跳往子页面会缓存滚动高度,父页面跳往其它页面会清除页面缓存记录,完结,撒花!
友情提示:本文只是提供一个方向,更多使用场景(如子页面跳往其它页面如何清除父页面的缓存记录等)小伙伴们自由发挥补完吧!