分享一个还不错的 el-table 高度自适应方案

92 阅读1分钟

问题描述

在Vue开发新页面的时候,表格高度自适应问题让我很不爽,总得带一堆变量或者函数,感觉就很冗余,页面复杂的时候有时候还不好用就很难受。无意间发现搭配css,能简化这个行为,所以分享一下。

代码实现

使用css的弹性盒子 的flex-direction: column 和 flex: 1 1 auto,控制中间盒子能拿到最大高度,利用 ref 获取最大高度,因为是弹性盒子,所以不管头部和底部的变化,中间的内容肯定是撑满的。 min-height: calc(100vh - 100px) 是因为面包屑的高度和底部空间留白。

<template>
  <div style="padding: 10px">
    <div class="bg-white flex" style="padding: 10px; flex-direction: column; min-height: calc(100vh - 100px)">
      <header class="flex mb-3">
        头部
      </header>
      <main style="flex: 1 1 auto" ref="mainDom">
        <el-table :data="[]" :height="tableHeight">
          <el-table-column type="index" width="60" label="序号" />
        </el-table>
      </main>
      <footer style="display: flex;padding-top: 10px;">
        <!-- 分页 -->
      </footer>
    </div>
    <div class="dialog">
      <!-- 对话框 -->
    </div>
  </div>
</template>
import { ref, onMounted } from 'vue';  
// 获取数据  
onMounted(async () => {
  tableHeight.value = mainDom.value.offsetHeight;
});

const tableHeight = ref(500); // 表格高度
const mainDom = ref(null);

最后

不清楚还有没有更好的方案,有的话麻烦指导下。