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

发布于:2025-05-14 ⋅ 阅读:(9) ⋅ 点赞:(0)
// 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为Promise
  const 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

网站公告

今日签到

点亮在社区的每一天
去签到