Vue3:页面如何自适应表格滚动高度
学习一个Vue3实际应用:页面如何自适应表格滚动高度。
适用场景:在网页的表格中我们需要获取页面的还可以用的高度来为表格做滚动的时候就需要使用响应高度,可以使用原生的calc来计算,但是calc有个缺陷就是,你要去计算多个盒子的高度,使用下面的代码就可以直接获取当前元素到底部的距离,然后减去总高度即可,是相当的方便 。
TS端代码:
import { ref , onMounted } from "vue"; /* * * Vue3计算剩余高度 * */ export default function () { //在Init的时候先行调用,然后在监听窗口的变化,保证是最新的宽高度 onMounted(()=>{ setWindowResize(); window.addEventListener('resize',setWindowResize) }); //测算基点 let basePoint = ref(); //元素测试盒子 let elementWidth = ref(0); //窗口的高度 let windowHeight = ref(0); const setWindowResize = function () { elementWidth.value = basePoint.value.getBoundingClientRect().top; windowHeight.value = window.innerHeight } return { basePoint , elementWidth , windowHeight }; }
页面端代码:
<script setup> import useCommon from '@/common/useCommon'; const { basePoint , windowHeight , elementWidth } = useCommon(); </script> <template> <div id="app"> <div style="height: 30px;background-color: rosybrown">{{ elementWidth }}</div> <div ref="basePoint"></div> <div :style="`height:calc( ${ windowHeight } - ${ elementWidth }px);background-color: tan`"></div> </div> </template> <style> html, body, #app { height: 100vh; width: 100vw; margin: 0; padding: 0; background-color: rebeccapurple; } </style>
OK,大家可以放进去运行下效果吧。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。