Vue

Element Table 自适应高度解决方案

2021-09-15  本文已影响0人  宏_4491
image.png
<template>
  <div class="my-container">
    <el-table id="tableData" :data="tableData" :height="height">
      <el-table-column prop="date" label="日期" width="140"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    const item = {
      date: '2016-05-02',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1518 弄',
    }
    return {
      tableData: Array(100).fill(item),
      // 随便定义一个初始高度防止报错
      height: '200px',
    }
  },

  methods: {
    getAutoHeight() {
      let el = document.querySelector('#tableData'),
        elParent = el.parentNode,
        pt = this.getStyle(elParent, 'paddingTop'),
        pb = this.getStyle(elParent, 'paddingBottom')
      // 一定要使用 nextTick 来改变height 不然不会起作用
      this.$nextTick(() => {
        this.height = elParent.clientHeight - (pt + pb) + 'px'

        console.log(this.height, "height")
      })
    },

    // 获取样式 我们需要减掉 padding-top, padding-bottom的值
    getStyle(obj, attr) {
      // 兼容IE浏览器
      let result = obj.currentStyle
        ? obj.currentStyle[attr].replace('px', '')
        : document.defaultView
            .getComputedStyle(obj, null)
            [attr].replace('px', '')
      return Number(result)
    },
  },

  mounted() {
    this.getAutoHeight()

    const self = this
    window.onresize = function () {
      self.getAutoHeight()
    }
  },
}
</script>

<style>
</style>

上一篇下一篇

猜你喜欢

热点阅读