0
点赞
收藏
分享

微信扫一扫

ElementUI表格el-table表头固定自适应高度解决方案

醉倾城1 2022-01-17 阅读 101

el-table header固定body高度自适应并滚动

elementui官方给出的header固定body滚动方案仅需给height属性赋值,但当我们遇到并不能写死height的情况,或许你会抛弃height,通过css使整个表格高度自适应并滚动,但表头也会被滚上去,就很不优雅。这时你可能会想到通过:show-header="false"隐藏表头并在上方另写一表通过配置css仅显示该表的表头,曲线救国,实现表头固定表体高度自适应并滚动(实际上,这是我 灵机一动 想到的,也确实这么做了,也不是不行,就是写起来蛮怪的是🙆‍♂️)。

我们只需依赖 getBoundingClientRect 动态赋值el-table的height。

参考:ElementUI表格el-table表头固定自适应高度解决方案

<el-table 
	:data="tableData"
	:height="tableHeight">
</el-table>             

记得data里加tableHeight,也可以先给个差不多的默认高度,比如我这给400

  data() {
    return {
      tableHeight: 400,
      timer: 0
    }
  },
  mounted() {
    this.calHeight()
    window.addEventListener('resize', this.onResize)
  },
  beforeDestroy() {
    this.timer && clearTimeout(this.timer)
    window.removeEventListener('resize', this.onResize)
  },
  methods: {
    // 根据父元素高度改变表格高度
    calHeight() {
      this.$nextTick(() => {
        // Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置
        const rect = this.$refs.tableContainer.getBoundingClientRect()
        // this.tableHeight = rect.height - 24  // 若有分页,减去分页高度
        this.tableHeight = rect.height
      })
    },
    // 监听界面resize调calHeight更新表格高度
    onResize() {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.calHeight()
      }, 100)
    },
  }
举报

相关推荐

0 条评论