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