适用场景:在网页表格中我们需要获取页面剩余高度来为表格做滚动的时候就需要使用响应高度,可以使用原生calc来计算,但是calc有个缺陷就是,有可能要去计算多个盒子高度,使用下面的代码就可以直接获取当前元素到顶部的距离,然后减去总高度即可,是相当的方便 。
TS端代码:
import { ref , onMounted } from "vue";
/*
*
* Vue3计算剩余高度
*
*/
export default function () {
//在Init的时候先行调用,然后在监听窗口的变化,保证是最新的宽高度
onMounted(()=>{
setWindowResize();
window.addEventListener('resize',setWindowResize)
});
//测算基点
let basePoint = ref();
//元素测试盒子
let elementToTopHight = ref(0);
//窗口的高度
let windowHeight = ref(0);
const setWindowResize = function () {
elementToTopHight.value = basePoint.value.getBoundingClientRect().top;
windowHeight.value = window.innerHeight
}
return { basePoint , elementToTopHight , windowHeight };
}
页面端代码:
<script setup lang="ts">
import useCommon from '@/common/useCommon';
const { basePoint , windowHeight , elementToTopHight } = useCommon();
</script>
<template>
<div id="app">
<div style="height: 30px;background-color: rosybrown">{{ elementToTopHight }}</div>
<div ref="basePoint"></div>
<div :style="`height:calc( ${ windowHeight } - ${ elementToTopHight }px);background-color: tan`"></div>
</div>
</template>
<style>
html, body, #app {
height: 100vh;
width: 100vw;
margin: 0;
padding: 0;
background-color: rebeccapurple;
}
</style>
运行效果图: