Vue3 el-table 动态高度(element-plus)

本文对比了Vue2中使用Element-UI动态设置表格高度的方法,并展示了如何在Vue3中使用ref和debounce优化高度计算,以确保在页面加载和窗口调整时保持响应式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先回顾一下vue2+element-ui的策略

export default (config) => {
  const {
    subtractHeight = 250,
  } = config;
  return {
    data() {
      return {
        subtractHeight,
        // 列表高度
        tableHeight: `${document.body.clientHeight - this.subtractHeight}px`,
      };
    },
    created() {
      window.addEventListener('resize', this.getHeight);
      // 监听事件注销,防止内存溢出
      this.$once('hook:beforeDestory', () => {
        window.removeEventListener('resize', this.getHeight);
      });
    },
    mounted() {
      this.getHeight();
    },
    watch: {
      subtractHeight: {
        handler() {
          this.getHeight();
        },
      },
    },
    methods: {
      /**
       * @todo 获取列表高度
       */
      getHeight() {
        this.tableHeight = `${document.body.clientHeight - this.subtractHeight}px`;
      },
    },
  };
};

vue3 就翻译一下吧

// tableHeight.js
import { ref, onBeforeUnmount, nextTick } from "vue";
import _ from "lodash";


export default function (opts) {
  const {
    subtractHeight = 500,
  } = opts;

  const tableHeight= ref(500)
  
  // 计算高度
  const getHeight = _.debounce(function() {
    const height = document.body.clientHeight - subtractHeight
    tableHeight.value = height > 200 ? height : 200;
  }, 500)
  
  // 监听窗口变化,触发高度计算
  window.addEventListener('resize', getHeight);
  onBeforeUnmount(() => {
    window.removeEventListener('resize', getHeight);
  })

  // 初始化高度
  nextTick(()=>{
    getHeight()
  })
  return {
    tableHeight
  };
}

页面中使用

<template>
  <el-table :data="tableData" style="width: 100%" :max-height="tableHeight">
    <el-table-column prop="date" label="Date" width="180" />
    <el-table-column prop="name" label="Name" width="180" />
    <el-table-column prop="address" label="Address" />
  </el-table>
</template>

<script setup>
import mixTableHeight from './tableHeight.js'
const { tableHeight } = mixTableHeight({ subtractHeight: 380 })
</script>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值