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

一、页面渲染

<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>

二、定义表格渲染数据及所需变量

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'
          }
        ]
      },
    }
  },

三、监听内容区域高度 screenHeight

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

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

四、浏览器尺寸变化响应事件

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

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

五、效果展示

浏览器全屏显示时:

Vue+Element-UI根据浏览器大小动态设置el-table的高度,实现自适应_第1张图片

浏览器缩小时:
Vue+Element-UI根据浏览器大小动态设置el-table的高度,实现自适应_第2张图片

你可能感兴趣的:(前端,Vue,javascript,vue.js,elementui,前端)