vben-admin 表格 切换页面 滚动条问题


开发中出现的问题:在用vben-admin的表格组件,切换页面后滚动条会回到顶部

解决思路: 当前页面开启keep-alive,给滚动条绑定scroll事件,用一个值去接收当前位置的scroll top,onMounted里面挂载监听事件,onActivated里面去设置滚动条的top;

注意事项(踩坑):调用scrollTo方法的时候要加 behavior 属性,不然会出现两条滚动条

示例代码:

<template>
<BasicTable
      @register="registerTable"
      ref="scrollRef"
    />
</template>

<script lang="ts">
import { useEventListener } from '/@/hooks/event/useEventListener'; import { defineComponent, ref, Ref, nextTick, onActivated,onMounted} from 'vue';
export
default defineComponent({ setup() {
  const tabRef = ref(null);

  const bodyEl: Ref<HTMLElement | null> = ref(null);
  const scrollTop = ref(0);
 
    function onScroll() {
        scrollTop.value = unref(bodyEl)?.scrollTop;
      }

     onMounted(() => {
        nextTick(() => {
          const table: any = unref(tabRef);
          if (!table) return;
          const tableEl: Element = table.$el;
          if (!tableEl) return;
          if (!unref(bodyEl)) {
            bodyEl.value = tableEl.querySelector('.ant-table-body');
          }
          useEventListener({
            el: unref(bodyEl),
            name: 'scroll',
            listener: onScroll,
            wait: 0,
          });
        });
      });

    onActivated(() => {
        nextTick(() => {
          if (scrollTop.value) {
            const table: any = unref(tabRef);
            if (!table) return;
            const tableEl: Element = table.$el;
            if (!tableEl) return;
            if (!unref(bodyEl)) {
              bodyEl.value = tableEl.querySelector('.ant-table-body');
            }
            unref(bodyEl)?.scrollTo({
              top: scrollTop.value,
              left: 0,
              behavior: 'smooth',
            });
          }
        });
      });
    return { tabRef }
}
})

</script>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM