keepAlive 配置的列表页遇到了几个问题。
1、当列表页经路由跳转跳到详情页,从详情页返回到列表页时,el-table 的滚动位置无法被缓存,会回到顶部。
2、el-table 的固定列 会错位。
问题 1 解决:
1 、配置需要缓存的页面
const routes = [
{ path: '/A', component: A },
{ path: '/B', component: B },
{ path: '/C', component: C },
{ path: '/D', component: D },
{
path: '/E',
component: E,
meta: { keepAlive: true }, // 默认不缓存
},
{ path: '/F', component: F },
{ path: '/G', component: G },
];
2、举个简单里例子 在你的el-table 里面增加 ref 和 handleScroll函数
<template>
<div>
<!-- 使用 keep-alive 缓存组件 -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
<!-- 假设这是你的 el-table -->
<el-table ref="table" @scroll="handleScroll">
<!-- 表格内容 -->
</el-table>
</div>
</template>
3、
methods: {
handleScroll(event) {
this.scrollTop = event.target.scrollTop;
},
restoreScroll() {
if (this.$refs.table) {
this.$refs.table.bodyWrapper.scrollTop = this.scrollTop;
}
}
},
activated() {
// 当组件被重新激活时,恢复滚动位置
this.$nextTick(() => {
this.restoreScroll();
});
},
beforeRouteLeave(to, from, next) {
// 在离开路由前保存滚动位置
if (this.$refs.table) {
this.scrollTop = this.$refs.table.bodyWrapper.scrollTop;
}
next();
}
==========↑↑↑↑↑======= 直接复制代码就能解决滚动问题。=======↑↑↑↑↑==========
第二个问题解决方案
1、因为咱们的页面时缓存的 所以咱们要在activited() 里面触发。
acitivited(){
if (this.$refs.myTable && this.$refs.myTable.doLayout) {
this.$refs.table.doLayout();
}
window.onresize = () => {
if (this.$refs.myTable&& this.$refs.myTable.doLayout) {
this.$refs.table.doLayout(); //页面返回时触发
}
};
}
========↑↑↑↑↑↑↑========这样两个问题就解决了=========↑↑↑↑↑↑↑=======
===============↓↓↓↓↓=============优化:=========↓↓↓↓↓==============
因为页面会多处使用,咱们就需要做一些优化:
把他提出来,写一个mixnis
第一步:创建一个 Mixin 文件
// src/mixins/scrollRestore.js
export default {
data() {
return {
scrollTop: 0,
};
},
methods: {
handleScroll(event) {
this.scrollTop = event.target.scrollTop;
},
restoreScroll(refName = 'table') {
const table = this.$refs[refName];
if (table && table.bodyWrapper) {
table.bodyWrapper.scrollTop = this.scrollTop;
}
},
},
activated() {
this.$nextTick(() => {
this.restoreScroll();
});
},
beforeRouteLeave(to, from, next) {
const table = this.$refs.table;
if (table && table.bodyWrapper) {
this.scrollTop = table.bodyWrapper.scrollTop;
}
next();
},
};
第二步:在组件中引入并使用这个 Mixin
<script>
import scrollRestore from '@/mixins/scrollRestore';
export default {
mixins: [scrollRestore],
};
</script>
========↑↑↑↑↑↑↑========这里的优化只针对了table=========↑↑↑↑↑↑↑=======
如果你想兼容其他滚动容器(如 div、el-scrollbar 等),可以检测 $el
或者指定 container 元素:
restoreScroll(containerKey = 'scrollContainer') {
const container = this.$refs[containerKey] || this.$el;
if (container) {
container.scrollTop = this.scrollTop;
}
}