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 ~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中,要缓存table滚动条的位置,你可以使用以下步骤: 1. 首先,在Vue的data中定义一个变量,用于存储滚动条的位置,比如scrollPosition。 2. 在table元素上添加一个scroll事件监听器,当滚动事件触发时,将滚动条的位置更新到scrollPosition中。 3. 在Vue的生命周期钩子函数中,比如created或mounted中,通过获取缓存中的滚动条位置,并将其赋值给scrollPosition。 4. 在Vue的updated钩子函数中,将scrollPosition中存储的滚动条位置重新应用到table元素上,以恢复滚动条的位置。 下面是一个示例代码: ```vue <template> <div> <table ref="table" @scroll="saveScrollPosition"> <!-- 表格内容 --> </table> </div> </template> <script> export default { data() { return { scrollPosition: 0 } }, created() { // 从缓存中获取滚动条位置,并赋值给scrollPosition this.scrollPosition = localStorage.getItem('scrollPosition') }, mounted() { // 应用滚动条位置到table元素上 this.$refs.table.scrollTop = this.scrollPosition }, updated() { // 更新滚动条位置 this.$refs.table.scrollTop = this.scrollPosition }, methods: { saveScrollPosition() { // 监听滚动事件,并将滚动条位置保存到scrollPosition中 this.scrollPosition = this.$refs.table.scrollTop // 将滚动条位置保存到缓存中 localStorage.setItem('scrollPosition', this.scrollPosition) } } } </script> ``` 在这个示例中,我们使用localStorage来保存滚动条位置,以便在页面刷新或重新加载后能够恢复滚动条位置。你也可以使用其他方式来存储和读取滚动条位置,比如vuex或cookie等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值