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>

 

posted @ 2021-08-19 17:17  Joseph11111  阅读(1121)  评论(0)    收藏  举报