[element-ui] 表格el-table表头固定自适应高度解决方案

在这里插入图片描述

flex布局

<body>
    <div id="app" class="flex-c">
        <div class="header flex-s">头部导航</div>
        <div class="content flex-a flex">
            <div class="left flex-s">左部菜单</div>
            <div class="right flex-a flex-c">
                <div class="menu-list flex-s">表格菜单</div>
                <div class="table-container flex-a" ref="container">自适应区域</div>
                <div class="pagination flex-s">表格分页</div>
            </div>
        </div>
    </div>
</body>
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
}

#app {
  height: 100%;
  text-align: center;
}

.flex, .flex-c { display: flex }
.flex-c { flex-direction: column; }
.flex-a { flex: auto; }
.flex-s { flex-shrink: 0; }

动态计算表格高度

我们把表格插入到自适应区域,并将设置自适应区域为相对定位,表格容器设置为绝对定位:

<div class="table-container flex-a" ref="container">
    <div class="table-container-inner">
        <el-table
        :data="tableData"
        :height="tableHeight"
        border>
        </el-table>
    </div>
</div>
.table-container {
    position: relative;
}

.table-container-inner {
    position: absolute;
    left: 0;
    right: 0;
    top: 0
}

然后我们使用Element.getBoundingClientRect()这个接口来获取自适应区域的高度,设置为表格高度,这样即可达到自适应高度固定表头的效果

export default {
  data () {
    return {
      tableHeight: 0,
      tableData: [
        // xxx 表格数据
      ]
    }
  },
  mounted () {
    this.calHeight()
  },
  methods: {
    calHeight () {
      this.$nextTick(() => {
        const rect = this.$refs.container.getBoundingClientRect()
        this.tableHeight = rect.height
      })
    }
  }
} 

当然,在用户操作的过程中,免不了会有一些影响页面布局的因素,此时我们需要重新计算一次高度。其中最常见的一种操作是改变浏览器窗口的大小,我们可以通过监听resize事件来重新计算高度:

data () {
    return {
        timer: 0
    }
}
mounted () {
    // ...
    window.addEventListener('resize', this.onResize)
},
beforeDestroy () {
    this.timer && clearTimeout(this.timer)Z      
    window.removeEventListener('resize', this.onResize)
},
methods: {
    // ...
    onResize () {
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            this.calHeight()
        }, 500)
    }
}

为了避免resize高频触发回调,这里使用定时器进行一个简单的控制。完整例子可以查看:http://jsrun.net/v56Kp/edit


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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值