首先需要在列表页的路由进行配置:加入meta-keepAlive = true
{
path: '/',
name: 'xxx',
component: xxx,
meta: {
keepAlive: true
}
}
然后在App.vue里,把代码组件重新复制粘贴一份,且被keep-alive标签包住。
<template>
<div id="app">
<keep-alive>
<el-container v-if="$route.meta.keepAlive" />
</keep-alive>
<el-container v-if="!$route.meta.keepAlive" />
</div>
</template>
且被keep-alive标签包住的加上
v-if="$route.meta.keepAlive"
keep-alive标签之外的的加上
v-if="!$route.meta.keepAlive"
然后在列表页的文件代码里:
监听离开和载入路由的事件,且将离开时路由滚动条所在的高度记录下来,载入时将高度更改为之前记录的高度。
beforeRouteEnter(to,from,next){
next(vm => {
if(vm){
if(vm.currentListBackHeightPos == 0){
next();
}else{
setTimeout(function () {
document.getElementById("mescroll").scrollTop = vm.currentListBackHeightPos;
}, 50)//同步转异步操作
}
}
})
},
beforeRouteLeave(to,from,next){
if(to.name == 'detail'){ //指定路由,代表要去往哪个路由,比如此时为list跳转到detail,同时也是从detail跳回来的时候保持滚动条高度
Vue.setGlobalVariable({'list_back_height_pos': document.getElementsByTagName("html")[0].scrollTop});
from.meta.keepAlive = true;
next();
}else{
//要去往的不是detail页,所以不用保存滚动条高度,所以清除keepAlive缓存
if (this.$vnode && this.$vnode.data.keepAlive) {
if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache) {
if (this.$vnode.componentOptions) {
var key = this.$vnode.key == null ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '') : this.$vnode.key
var cache = this.$vnode.parent.componentInstance.cache
var keys = this.$vnode.parent.componentInstance.keys
if (cache[key]) {
if (keys.length) {
var index = keys.indexOf(key)
if (index > -1) {
keys.splice(index, 1)
}
}
delete cache[key]
}
}
}
}
Vue.setGlobalVariable({'list_back_height_pos': 0});
next();
}
},