el-table 不定高表格固定表头(vue2)

5 阅读1分钟

不定高表格固定表头这是工作中很常遇到的需求。
不清楚这些做ui组件库的为什么不内置一套解决方案。。。
还得耗时费力地到网上搜,自己不断尝试去找寻处理办法。。。

虽然不想再用vue2了,但工作中的老项目,没有办法。
本文便是针对 element-ui的一个方案。
其他UI的方案请查阅:

<template>
  <div class="h-screen flex flex-col">
    <div ref="tableContainer" class="flex flex-col mt-2 overflow-hidden" :style="tableContainerStyle">
      <el-table :data="tableData" height="full" />
    </div>
  </div>
</template>
<script>
import { debounce } from 'lodash-es'
export default {
  data() {
    return {
      tableData: [],
      tableContainerStyle: 'flex-1',
    }
  },
  mounted() {
    this.debounceResize = debounce(this.resizeEvent, 300)
    window.addEventListener('resize', this.debounceResize)
  },
  methods: {
    resizeEvent() {
      const that = this
      that.tableContainerStyle = 'flex:1'
      this.$nextTick(() => {
        const containerHeight = this.$refs.tableContainer.offsetHeight

        const wrapper = that.$refs.table.$el.querySelector('.el-table__body-wrapper')
        const header = that.$refs.table.$el.querySelector('.el-table__header-wrapper')
        const headerHeight = header.offsetHeight
        const dataTable = wrapper.children[0]
        const tableHeight = dataTable.offsetHeight
        // const wrapperHeight = wrapper.offsetHeight

        if (tableHeight && tableHeight <= containerHeight - headerHeight) {
          that.tableContainerStyle = `height:${tableHeight + headerHeight + 17}px`
          // 17为水平滚动条高度,如果没有水平滚动条,可不加
        }
      })
    },
    getList() {
      this.tableData = [...res.data] //获取远程数据
      this.resizeEvent() //重新设置高度
    },
  },
}
</script>

支持一下

本人正在找工作,如在长三角有合适岗位,请联系我

热情地欢迎各位兄弟姐妹的大力支持!
github: github.com/leafio?tab=…
期待至少一个项目能达成1000个star
期待至少一个npm能达成每周1000次下载