Files
ks-app-employment-service/hook/useColumnCount.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2025-05-13 11:10:38 +08:00
// composables/useColumnCount.js
import {
ref,
onMounted,
onUnmounted,
watch
} from 'vue'
export function useColumnCount(onChange = () => {}) {
const columnCount = ref(0)
2025-05-16 09:28:44 +08:00
const columnSpace = ref(2)
2025-05-13 11:10:38 +08:00
2025-05-16 09:28:44 +08:00
// const calcColumn = () => {
// const width = uni.getSystemInfoSync().windowWidth
// console.log(width)
// const count = Math.min(5, Math.floor(width / 375) + 1)
// if (count !== columnCount.value) {
// columnCount.value = count < 2 ? 2 : count
// }
// }
2025-05-13 11:10:38 +08:00
const calcColumn = () => {
2025-10-20 11:05:11 +08:00
// 使用新的API替代已废弃的getSystemInfoSync
let width
// #ifdef MP-WEIXIN
const mpSystemInfo = uni.getWindowInfo()
width = mpSystemInfo.windowWidth
// #endif
// #ifndef MP-WEIXIN
const otherSystemInfo = uni.getSystemInfoSync()
width = otherSystemInfo.windowWidth
// #endif
2025-05-16 09:28:44 +08:00
let count = 2
if (width >= 1000) {
count = 5
} else if (width >= 750) {
count = 4
} else if (width >= 500) {
count = 3
} else {
count = 2
}
2025-05-13 11:10:38 +08:00
if (count !== columnCount.value) {
columnCount.value = count
}
2025-05-16 09:28:44 +08:00
// 计算间距count=2 => 1count=5 => 2中间线性插值
const spacing = 2 - (count - 2) * (1 / 3)
// console.log('列数:', count, '间距:', spacing.toFixed(2))
columnSpace.value = spacing
2025-05-13 11:10:38 +08:00
}
onMounted(() => {
columnCount.value = 2
calcColumn()
2025-10-20 11:05:11 +08:00
// 只在H5环境下添加resize监听器
// #ifdef H5
if (typeof window !== 'undefined') {
window.addEventListener('resize', calcColumn)
}
// #endif
2025-05-13 11:10:38 +08:00
})
onUnmounted(() => {
2025-10-20 11:05:11 +08:00
// #ifdef H5
if (typeof window !== 'undefined') {
window.removeEventListener('resize', calcColumn)
}
// #endif
2025-05-13 11:10:38 +08:00
})
// 列数变化时执行回调
watch(columnCount, (newVal, oldVal) => {
if (newVal !== oldVal) {
onChange(newVal)
}
})
return {
columnCount,
2025-05-16 09:28:44 +08:00
columnSpace
2025-05-13 11:10:38 +08:00
}
}