当前位置: 首页 > news >正文

uniapp(vue3)动态计算swiper高度封装自定义hook

// useCalculateSwiperHeight.ts
import { ref, onMounted } from 'vue';export function useCalculateSwiperHeight(headerSelector: string = '.header-search', tabsWrapperSelector: string = '.u-tabs .u-tabs__wrapper') {const swiperHeight = ref<number>(0);// 封装uni.getSystemInfo为Promiseconst getSystemInfo = () => {return new Promise<UniApp.GetSystemInfoResult>((resolve) => {uni.getSystemInfo({ success: resolve });});};// 封装元素高度查询// 修复后的元素高度查询封装const getRect = (selector: string) => {return new Promise<UniNamespace.NodeInfo | null>((resolve) => {uni.createSelectorQuery().select(selector).boundingClientRect((res) => {// 处理可能返回数组的情况const result = Array.isArray(res) ? res[0] : res;resolve(result as UniNamespace.NodeInfo);}).exec();});};// 计算高度方法const calculateHeight = async () => {try {const [searchRect, tabsRect, sysInfo] = await Promise.all([getRect(headerSelector), getRect(tabsWrapperSelector), getSystemInfo()]);if (!searchRect || !tabsRect || !sysInfo) {console.error('未能获取到必要的布局信息');return;}swiperHeight.value = sysInfo.windowHeight - (searchRect.height || 0) - (tabsRect.height || 0);} catch (error) {console.error('计算高度时发生错误:', error);}};// 组件挂载后自动计算onMounted(() => {calculateHeight();});// 返回高度值和重新计算的方法return {swiperHeight,recalculate: calculateHeight};
}
  • 组件内使用
import { useCalculateSwiperHeight } from '@/hooks/useCalculateSwiperHeight';// #ifdef H5
const { swiperHeight } = useCalculateSwiperHeight('.header-search', '.u-tabs  .u-tabs__wrapper');
// #endif
// #ifdef MP-WEIXIN
const { swiperHeight } = useCalculateSwiperHeight('.header-search', '.u-tabs >>> .u-tabs__wrapper');
// #endif

相关文章:

  • Foupk3systemX5OS TXW8移动设备
  • UE5中制作动态数字Decal
  • While语句数数字
  • 互信息:揭秘变量间的隐藏关联
  • 5.13本日总结
  • windows 强行终止进程,根据端口号
  • 【Linux 系统调试】系统的动态跟踪工具--SystemTap
  • 系统平衡与企业挑战
  • C++ 字符格式化输出
  • Linux 系统安全基线检查:入侵防范测试标准与漏洞修复方法
  • 【递归、搜索与回溯】专题一:递归(二)
  • SparkSQL 连接 MySQL 并添加新数据:实战指南
  • 微服务八股(自用)
  • hashicorp vault机密管理系统的国产化替代:安当SMS凭据管理系统,量子安全赋能企业密钥管理
  • 软考软件测评师——计算机网络
  • 【Pandas】pandas DataFrame cummin
  • NC报销单保存时,报”保存失败:fail to save VO Array ~#@“
  • SQL中联表的运用
  • EXCEL下拉菜单与交替上色设置
  • ElasticSeach快速上手笔记-入门篇
  • 国台办:80年前台湾重归中国版图,80年后不可能让台湾分裂出去
  • 宝通科技:与宇树合作已签约,四足机器人在工业场景落地是重点商业化项目
  • 董军同法国国防部长举行会谈
  • 何立峰:中方坚定支持多边主义和自由贸易,支持世界贸易组织在全球经济治理中发挥更大作用
  • 基因编辑技术让蜘蛛吐彩丝
  • 观察|天空之外的战场:官方叙事、新闻与社交平台中的印巴冲突