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>

猜你喜欢

转载自blog.csdn.net/weiliangLAN/article/details/141026636