Vue3页面自适应,表格滚动高度

文章介绍了如何在Vue3中使用响应高度计算,特别是在表格滚动时,避免使用calc函数的复杂性。同时提供了微信小程序中获取元素到顶部距离的方法。
摘要由CSDN通过智能技术生成
适用场景:在网页表格中我们需要获取页面剩余高度来为表格做滚动的时候就需要使用响应高度,可以使用原生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>

 微信小程序(Uniapp):

//获取屏幕的总高度
export function getScreenHeight() : number {
	let platform = uni.getSystemInfoSync().uniPlatform;
	if(platform == 'mp-weixin') {
		//微信小程序需要减去顶部的statusBarHeight
		return uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight || 0;
	}else {
		return uni.getSystemInfoSync().windowHeight;
	}
	
}


//微信小程序只能在页面内调用,不能导入调用,导入调用无效
export function getElementToTopHight( element : string ) : number {
	//初始高度
	let initHight = 0;
	uni.createSelectorQuery().select( element ).boundingClientRect( ( res : any ) => {
		initHight = res.top;
	}).exec();
	return initHight;
}


//获取页面剩余高度
import { getCurrentInstance } from "vue";


export async function getPageResidueDIST(nodeKey: string) : Promise<number> {
	const query = uni.createSelectorQuery().in(getCurrentInstance());
	let systemInfo = await uni.getSystemInfo();
	let nodeToTop : number = await new Promise((ok, _) => {
		query
			.select(nodeKey)
			.boundingClientRect((data: any) => {
				ok(data.top);
			})
			.exec();
	});
	return systemInfo.windowHeight - nodeToTop;
}

运行效果图:

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值