import { ref, onMounted, getCurrentInstance } from 'vue' export function useSystemInfo() { const { proxy } = getCurrentInstance() const systemInfo = ref({}) const validHeight = ref(0) const navHeight = ref(0) // 获取页面可用高度 const getValidHeight = (info) => { const windowHeight = info.windowHeight // 在非tabbar页,ios端预留底部安全高度 const safeBottom = info.osName === 'ios' && info.safeAreaInsets.bottom && info.uniPlatform !== 'web' && info .uniPlatform !== 'app' ? 20 : 0 return windowHeight - safeBottom } // 获取导航栏高度 const getNavHeight = (info) => { let navHeight = 0 if (info.uniPlatform === 'mp-weixin') { const custom = uni.getMenuButtonBoundingClientRect(); navHeight = custom.height + (custom.top - info.statusBarHeight) * 2; } else if (info.uniPlatform === 'mp-alipay') { navHeight = info.titleBarHeight } else if (info.uniPlatform === 'mp-baidu') { navHeight = info.navigationBarHeight } return navHeight } onMounted(() => { systemInfo.value = uni.getSystemInfoSync() validHeight.value = getValidHeight(systemInfo.value) navHeight.value = getNavHeight(systemInfo.value) }) // 计算dom高度(需要在mounted生命周期后调用) const computedDomHeight = (selectors, selectType = 'select') => { return new Promise(async (resolve, reject) => { let context = uni.createSelectorQuery().in(proxy) if (systemInfo.value.uniPlatform === 'mp-alipay') { context = uni.createSelectorQuery(); } let domHeight = 0; let domWidth = 0; let queriesCount = 0; let selectorQueries = []; // 如果selectors是字符串,则将其转换为单元素数组 if (typeof selectors === 'string') { selectors = [selectors]; } if (!Array.isArray(selectors)) { console.error('selectors 必须是字符串或字符串数组') reject(false) return } // 长度为0 if (!selectors.length) { resolve(0) return } // 添加到执行上下文 for (let selectorStr of selectors) { context[selectType](selectorStr).boundingClientRect(); } // 执行查询 context.exec(result => { // 累加高度 result.forEach((cur) => { if (cur) { domHeight += cur.height; domWidth += cur.width; } }); resolve({ height: domHeight, width: domWidth, rect: result }); }); }) } return { systemInfo, validHeight, navHeight, computedDomHeight } }