element组件表格实现高度自适应,并且随父元素动态更改

1.table的height属性

height: table 的高度。 默认为自动高度。 如果 height 为 number 类型,单位 px;如果 height 为 string 类型,则这个高度会设置为 Table 的 style.height 的值,Table 的高度会受控于外部样式。

2.问题描述

1.如果不添加height属性,table内不出现滚顶条
2.当table顶部元素控制显隐时table重新计算高度

3.解决办法

1.在src下新建directive 文件夹,新建 autoHeight.js

export default {
  mounted: function(el, binding) {
    const { value } =  binding
    changeElHeight(el, value)
  },
  updated: function(el, binding) {
    const { value } =  binding
    changeElHeight(el, value)
  },
}
const changeElHeight = (el, value) => {
  const searchRef = el.previousElementSibling
  if (value) {
    el.style.height = `calc(100% - ${(searchRef.clientHeight + 20) / 100}rem)`
  } else {
    el.style.height = '100%'
  }
}

2.全局注册自定义指令

// main.js
import { createApp } from 'vue'
import autoHeight from './common/autoHeight'

const app = createApp(App)
app.directive('autoHeight', autoHeight)

3.table设置height属性

<el-table height="100%"></table>

4.父级元素使用自定义指令

<template>
  <div class="container">
    // 搜索栏 可现实隐藏
    <div v-show="showSearch" class="search"> ......</div>
    // 表格父元素
    <div class="main" v-autoHeight="showSearch">
      // 控制显隐按钮
      <div class="operate">
        ......
        <el-button icon="Search circle @click="showSearch=!showSearch"></el-button>
        ......
      </div>
      // 表格
      <div class="table">
        <el-table height="100%">......</table>
      </div>
    </div>
  </div>
</template>
<script setup>
// 当切换showSearch 控制 头部显隐时 table-container会重新计算高度 table铺满
const showSearch = ref(true)
</script>
<style lang="scss" scoped>
  .container {
    height: 100%;
    width: 100%;
    padding: 0.2rem
  }
  .search {
    height: 1rem;
    width: 100%;
    padding: 0.2rem
    margin-bottom: 0.2rem
  }
  .main {
    height: calc(100% -  1rem);
    width: 100%;
    padding: 0.2rem
    .operate {
      height: 0.5rem
    }
    .table {
      height: calc(100% - 0.5rem)
    }
  }
</style>

实现效果

在这里插入图片描述
在这里插入图片描述

搞定了 点个赞哎呀 宝贝

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值