antdesign table表格高度自适应并且可以滚动

1,485 阅读1分钟

要实现表格高度自适应,首先需要监听窗口变化,然后计算窗口高度。
因为每个表格都需要用到此代码,所以建议使用vue3的hooks函数。(vue2可使用mixin)
以下是具体步骤:

1. 首先定义hook函数calcTableHeight

import _ from 'lodash';

export function useTableHeight() {
  const tableHeight = ref<number>(document.body.clientHeight - 420);
  // 计算表格动态高度
  function calculateTableHeight() {
    tableHeight.value = document.body.clientHeight - 420; // 此处 420 是表头高度,根据具体情况而定。
  }
  // 初始化和监听 resize 事件,这里使用防抖提高性能
  onMounted(() => {
    window.addEventListener('resize', _.debounce(calculateTableHeight, 200));
  });
  // 移除监听器
  onBeforeUnmount(() => {
    window.removeEventListener('resize', _.debounce(calculateTableHeight, 300));
  });
  return tableHeight;
}


2. 在使用表格的页面引入calcTableHeight

<template>
  <div>
    <a-table
      :columns="columns"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ y: tableHeight }"
    >
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { useTableHeight } from '@/hooks/calcTableHeight';
const tableHeight = useTableHeight();
...
</script>

注意:表格高度最后需要减去表头高度!