44 lines
1.4 KiB
JavaScript
44 lines
1.4 KiB
JavaScript
import { ref, onMounted, onUnmounted } from 'vue'
|
|
import { debounce } from 'lodash' // 或手动实现防抖
|
|
|
|
/**
|
|
* 动态计算网格列数的 Hook
|
|
* @param {number[]} breakpoints - 断点数组,如 [400, 600] 表示 400px 和 600px 两个断点
|
|
* @param {number[]} cols - 对应断点的列数,如 [2, 3, 4] 表示:
|
|
* - 屏幕宽度 < 400px: 2 列
|
|
* - 400px ≤ 宽度 < 600px: 3 列
|
|
* - 宽度 ≥ 600px: 4 列
|
|
* @returns {Object} { gridCol } - 返回响应式的列数引用
|
|
*/
|
|
export function useGridCol(breakpoints = [400, 600], cols = [2, 3, 4]) {
|
|
const gridCol = ref(cols[cols.length - 1]) // 默认取最大值(大屏列数)
|
|
|
|
const calculateGridCol = () => {
|
|
const { windowWidth } = uni.getSystemInfoSync()
|
|
let selectedCol = cols[cols.length - 1] // 默认值
|
|
|
|
// 遍历断点,找到匹配的列数
|
|
for (let i = 0; i < breakpoints.length; i++) {
|
|
if (windowWidth < breakpoints[i]) {
|
|
selectedCol = cols[i]
|
|
break
|
|
}
|
|
}
|
|
gridCol.value = selectedCol
|
|
}
|
|
|
|
onMounted(() => {
|
|
calculateGridCol() // 初始化计算
|
|
uni.onWindowResize(calculateGridCol) // 监听窗口变化
|
|
})
|
|
|
|
onUnmounted(() => {
|
|
// 清理监听(部分平台可能需要手动实现)
|
|
if (typeof uni.offWindowResize === 'function') {
|
|
uni.offWindowResize(calculateGridCol)
|
|
}
|
|
})
|
|
|
|
return { gridCol }
|
|
}
|