| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- // composables/useWindowWidth.ts
- import { ref, onMounted, onBeforeUnmount, type Ref } from 'vue'
- // 同步获取当前窗口宽度
- function getCurrentWidth(): number {
- // #ifdef H5
- if (typeof window !== 'undefined') {
- return window.innerWidth
- }
- // #endif
- // #ifdef APP-PLUS
- // @ts-ignore
- if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
- // @ts-ignore
- const systemInfo = uni.getSystemInfoSync()
- return systemInfo.windowWidth
- }
- // #endif
- return 0 // 兜底值
- }
- export function useWindowWidth(debounceMs: number = 0): Ref<number> {
- // ✅ 关键:立即同步获取宽度,不再初始为 0
- const width = ref(getCurrentWidth())
- let timer: ReturnType<typeof setTimeout> | null = null
- let resizeHandler: (res?: any) => void
- const updateWidth = () => {
- width.value = getCurrentWidth()
- }
- if (debounceMs > 0) {
- resizeHandler = () => {
- if (timer) clearTimeout(timer)
- timer = setTimeout(() => {
- updateWidth()
- timer = null
- }, debounceMs)
- }
- } else {
- resizeHandler = updateWidth
- }
- onMounted(() => {
- // 确保宽度最新(如屏幕旋转后组件才挂载的极端情况)
- updateWidth()
- // #ifdef H5
- if (typeof window !== 'undefined') {
- window.addEventListener('resize', resizeHandler)
- }
- // #endif
- // #ifdef APP-PLUS
- // @ts-ignore
- if (typeof uni !== 'undefined' && uni.onWindowResize) {
- // @ts-ignore
- uni.onWindowResize(resizeHandler)
- }
- // #endif
- })
- onBeforeUnmount(() => {
- if (timer) clearTimeout(timer)
- // #ifdef H5
- if (typeof window !== 'undefined') {
- window.removeEventListener('resize', resizeHandler)
- }
- // #endif
- // #ifdef APP-PLUS
- // @ts-ignore
- if (typeof uni !== 'undefined' && uni.offWindowResize) {
- // @ts-ignore
- uni.offWindowResize(resizeHandler)
- }
- // #endif
- })
- return width
- }
|