Vue3内容高度自适应

utils.js: 封装为工具函数

/**
 * @description 内容高度自适应
 * @param refEle <Ref> ref绑定的元素
    (注意:ref不能绑在UI组件上,否则会丢失 getBoundingClientRect 方法)
 * @param bottomHeight <Number> 要减去的底部高度(边距、预留空间等)
 * @return contentHeight <Number> 内容高度
 */

import { ref, isRef, nextTick, onMounted, onUnmounted } from 'vue'

export function useContentHeight(refEle, bottomHeight = 0) {
  if(!(refEle && isRef(refEle))) return 0;

  let contentHeight = ref(0); //内容高度

  const onResize = () => {
    nextTick(() => {
      // 内容自适应高度 = 窗口高度 - 当前元素头部到窗口的高度 - 底部高度
      let contentTop = refEle?.value?.getBoundingClientRect()?.top || 0;
      contentHeight.value = Math.round(window.innerHeight - contentTop - bottomHeight);
    })
  };
    
  onMounted(() => {
    onResize();
    window.addEventListener('resize', onResize); 
  });
  onUnmounted(() => {
    window.removeEventListener('resize', onResize);
  })
  return contentHeight;
}

Vue:

<template>
    <!-- 表格 -->
    <div ref="tableHeightRef" :style="{height: tableHeight + 'px'}">
        <el-table :max-height="tableHeight" border style="width: 100%">
           ... 
        </el-table>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useContentHeight } from "@/utils.js"

//表格自适应高度
const tableHeightRef = ref();
const tableHeight = useContentHeight(tableHeightRef);

</script>

<style lang="scss" scoped>
</style>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值