vue+element ui根据浏览器大小动态设置el-table的高度,实现自适应

3,635 阅读1分钟

1.页面渲染

表格的 height 属性绑定一个变量 tableHeight 来动态设置表格的高度:

<template>
  <div class="app-container">
    <div style="background-color:green;padding:20px;margin-bottom:30px">
      <el-table
        :data="table1_info.tableData11"
        style="width: 100%;"
        border
        :height="tableHeight"
      >
        <el-table-column
          v-for="(item,index1) in table1_info.tableData11[0]"
          :key="index1"
          align="center"
          :label="index1"
        >
          <template slot-scope="scope">
            {{ scope.row[index1] }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

2.定义表格渲染数据及所需变量

data() {
    return {
      tableHeight: window.innerHeight - 260, //表格动态高度
      screenHeight: window.innerHeight, //内容区域高度
      table1_info: {
        title: '表格1',
        tableData11: [
          {
            '值1': '1',
            '值2': '2',
            '值3': '3'
          },
          {
            '值1': '11',
            '值2': '22',
            '值3': '33'
          }
        ]
      },
    }
  },

3.监听内容区域高度 screenHeight

通过监听 screenHeight 来动态设置表格高度 tableHeight

watch: {
    // 监听screenHeight从而改变table的高度
    screenHeight(val) {
      this.screenHeight = val
      this.tableHeight = this.screenHeight - 260
    }
 },

4.浏览器尺寸变化响应事件

只要浏览器尺寸发生变化,则重新给 screenHeight 赋值

mounted: function() {
    // window.onresize:浏览器尺寸变化响应事件
    window.onresize = () => {
      return (() => {
        // window.innerHeight:浏览器的可用高度
        window.screenHeight = window.innerHeight
        this.screenHeight = window.screenHeight
      })()
    }
  },

5.效果展示

浏览器全屏显示时:

浏览器缩小时: