vue中固定表头行,动态获取高度

675 阅读1分钟

1、需要在页面的el-table配置属性:ref="table" 和 :height="tableHeight"

 <el-table
        :header-cell-style="{ background: '#F8F8F8' }"
        :data="tableData"
        ref="table"
         :max-height="tableHeight"
      >
</el-table>

2、方法配置代码如下

export default {
    data () {
        return {
            tableHeight: 400
        }
    },
    mounted () {
        this.$nextTick(() => {
            this.setTableHeight()
            // 监听窗口大小变化
            window.onresize = () => {
                this.setTableHeight()
            }
        })
    },
    beforeDestroy () {
        // 由于window.onresize是全局事件,在其他页面改变界面时也会执行,这样可能会出现问题,需要在离开这个界面时注销window.onresize事件
        window.onresize = null
    },
    methods: {
        setTableHeight () {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 115
            console.log('this.tableHeight')
            console.log(this.tableHeight)
        }
    }
}

3、需要添加样式(偶发:有表格没有出现y轴滚动条的情况)

 .el-table__body-wrapper {
        overflow-y: scroll !important;
    }