vue3实现element table缓存滚动条

背景

对于后台管理系统,数据的展示形式大多都是通过表格,常常会出现的一种场景,从表格跳到二级页面,再返回上一页时,需要缓存当前的页码和滚动条的位置,以为使用keep-alive就能实现这两种诉求,实际开发的时候,才发现 keep-alive组件是不会缓存滚动位置的。

实现table缓存滚动条

先使用keep-alive

<template>
	<el-main>
		<router-view v-slot="{ Component, route }">
			<transition appear name="fade-transform" mode="out-in">
				<keep-alive :include="keepAliveStore.keepAliveName">
					<component :is="Component" :key="route.path" v-if="isRouterShow" />
				</keep-alive>
			</transition>
		</router-view>
	</el-main>
</template>

在二次封装的列表组件中,监听 activated deactivated 生命周期,设置表格的滚动条

// 实现element table缓存滚动位置
const tableRef = ref<InstanceType<typeof ElTable>>(); // 表格的实例
const scrollPosition = ref<number | null>(null); // 记录滚动条的位置
// 页面激活时
onActivated(() => {
	if (scrollPosition.value) {
		nextTick(() => {
            // 设置表格的滚动条位置
			tableRef.value?.scrollBarRef.setScrollTop(scrollPosition.value);
			scrollPosition.value = null;
		});
	}
});
// 页面离开时
onDeactivated(() => {
	nextTick(() => {
        // 记录滚动条的位置
		scrollPosition.value = tableRef.value?.scrollBarRef.wrapRef.scrollTop;
	});
});

呈现的效果:

 ~~ END ~~

猜你喜欢

转载自blog.csdn.net/weixin_45313351/article/details/134641593