useWindowWidth.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // composables/useWindowWidth.ts
  2. import { ref, onMounted, onBeforeUnmount, type Ref } from 'vue'
  3. // 同步获取当前窗口宽度
  4. function getCurrentWidth(): number {
  5. // #ifdef H5
  6. if (typeof window !== 'undefined') {
  7. return window.innerWidth
  8. }
  9. // #endif
  10. // #ifdef APP-PLUS
  11. // @ts-ignore
  12. if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
  13. // @ts-ignore
  14. const systemInfo = uni.getSystemInfoSync()
  15. return systemInfo.windowWidth
  16. }
  17. // #endif
  18. return 0 // 兜底值
  19. }
  20. export function useWindowWidth(debounceMs: number = 0): Ref<number> {
  21. // ✅ 关键:立即同步获取宽度,不再初始为 0
  22. const width = ref(getCurrentWidth())
  23. let timer: ReturnType<typeof setTimeout> | null = null
  24. let resizeHandler: (res?: any) => void
  25. const updateWidth = () => {
  26. width.value = getCurrentWidth()
  27. }
  28. if (debounceMs > 0) {
  29. resizeHandler = () => {
  30. if (timer) clearTimeout(timer)
  31. timer = setTimeout(() => {
  32. updateWidth()
  33. timer = null
  34. }, debounceMs)
  35. }
  36. } else {
  37. resizeHandler = updateWidth
  38. }
  39. onMounted(() => {
  40. // 确保宽度最新(如屏幕旋转后组件才挂载的极端情况)
  41. updateWidth()
  42. // #ifdef H5
  43. if (typeof window !== 'undefined') {
  44. window.addEventListener('resize', resizeHandler)
  45. }
  46. // #endif
  47. // #ifdef APP-PLUS
  48. // @ts-ignore
  49. if (typeof uni !== 'undefined' && uni.onWindowResize) {
  50. // @ts-ignore
  51. uni.onWindowResize(resizeHandler)
  52. }
  53. // #endif
  54. })
  55. onBeforeUnmount(() => {
  56. if (timer) clearTimeout(timer)
  57. // #ifdef H5
  58. if (typeof window !== 'undefined') {
  59. window.removeEventListener('resize', resizeHandler)
  60. }
  61. // #endif
  62. // #ifdef APP-PLUS
  63. // @ts-ignore
  64. if (typeof uni !== 'undefined' && uni.offWindowResize) {
  65. // @ts-ignore
  66. uni.offWindowResize(resizeHandler)
  67. }
  68. // #endif
  69. })
  70. return width
  71. }