element el-table计算最大高度

一、实现思路

根据当前屏幕的可视高度(window.innerHeight) - 表格顶部距离可视高度顶部的距离 = 剩余高度 (可适当手动添加底部安全距离(bottomPadding)) 

import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'

/**
 * 获取表格最大高度
 * @param options
 * @returns {{tableRef: null, setTableHeight: setTableHeight, tableHeight: Ref<UnwrapRef<number>>}}
 */
export function useTableHeight(options = {}) {
  const { tableRef: externalTableRef = null, hasPagination = true } = options

  const internalTableRef = ref(null)
  const tableRef = externalTableRef || internalTableRef
  const maxHeight = ref(0)

  const calculateTableHeight = () => {
    if (!tableRef.value) return
    const windowHeight = window.innerHeight
    const tableTop = tableRef.value.$el.getBoundingClientRect().top
    const bottomPadding = hasPagination ? 68 : 20
    return windowHeight - tableTop - bottomPadding
  }

  const setTableHeight = () => {
    nextTick(() => {
      maxHeight.value = calculateTableHeight()
    })
  }

  onMounted(() => {
    window.addEventListener('resize', setTableHeight)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', setTableHeight)
  })

  // 监听 tableRef 的变化
  watch(
    () => tableRef.value,
    (newVal) => {
      if (newVal && newVal.$el) {
        setTableHeight()
      }
    },
    { immediate: true }
  )

  // 提供手动触发方法
  const updateTableHeight = () => {
    nextTick(setTableHeight)
  }

  return {
    tableRef,
    maxHeight,
    setTableHeight,
    updateTableHeight
  }
}

使用

const { tableRef, maxHeight } = useTableHeight()
 <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        :max-height="maxHeight"
        :summary-method="getSummaries"
        border
        show-summary
        stripe> ... 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值