/** * 屏幕尺寸缓存模块 * 缓存屏幕宽度和高度,避免重复调用系统API */ class ScreenCache { constructor() { this.cache = { windowWidth: 0, windowHeight: 0, screenWidth: 0, screenHeight: 0, statusBarHeight: 0, pixelRatio: 1, timestamp: 0 } this.initialized = false } /** * 初始化屏幕尺寸缓存 */ init() { if (this.initialized) { return this.cache } try { const systemInfo = uni.getSystemInfoSync() this.cache = { windowWidth: systemInfo.windowWidth || 375, windowHeight: systemInfo.windowHeight || 667, screenWidth: systemInfo.screenWidth || 375, screenHeight: systemInfo.screenHeight || 667, statusBarHeight: systemInfo.statusBarHeight || 0, pixelRatio: systemInfo.pixelRatio || 1, timestamp: Date.now() } this.initialized = true console.log('[屏幕缓存] 初始化完成:', this.cache) } catch (error) { console.error('[屏幕缓存] 初始化失败:', error) // 使用默认值 this.cache = { windowWidth: 375, windowHeight: 667, screenWidth: 375, screenHeight: 667, statusBarHeight: 0, pixelRatio: 1, timestamp: Date.now() } } return this.cache } /** * 获取窗口宽度 * @returns {number} 窗口宽度(px) */ getWindowWidth() { if (!this.initialized) { this.init() } return this.cache.windowWidth } /** * 获取窗口高度 * @returns {number} 窗口高度(px) */ getWindowHeight() { if (!this.initialized) { this.init() } return this.cache.windowHeight } /** * 获取屏幕宽度 * @returns {number} 屏幕宽度(px) */ getScreenWidth() { if (!this.initialized) { this.init() } return this.cache.screenWidth } /** * 获取屏幕高度 * @returns {number} 屏幕高度(px) */ getScreenHeight() { if (!this.initialized) { this.init() } return this.cache.screenHeight } /** * 获取状态栏高度 * @returns {number} 状态栏高度(px) */ getStatusBarHeight() { if (!this.initialized) { this.init() } return this.cache.statusBarHeight } /** * 获取像素比 * @returns {number} 像素比 */ getPixelRatio() { if (!this.initialized) { this.init() } return this.cache.pixelRatio } /** * 获取所有缓存数据 * @returns {Object} 缓存数据对象 */ getAll() { if (!this.initialized) { this.init() } return { ...this.cache } } /** * 刷新缓存(屏幕方向改变时调用) */ refresh() { this.initialized = false return this.init() } /** * 清除缓存 */ clear() { this.cache = { windowWidth: 0, windowHeight: 0, screenWidth: 0, screenHeight: 0, statusBarHeight: 0, pixelRatio: 1, timestamp: 0 } this.initialized = false console.log('[屏幕缓存] 已清除') } } // 创建单例实例 const screenCache = new ScreenCache() // 导出单例实例和便捷方法 export default screenCache export const getWindowWidth = () => screenCache.getWindowWidth() export const getWindowHeight = () => screenCache.getWindowHeight() export const getScreenWidth = () => screenCache.getScreenWidth() export const getScreenHeight = () => screenCache.getScreenHeight() export const getStatusBarHeight = () => screenCache.getStatusBarHeight() export const getPixelRatio = () => screenCache.getPixelRatio() export const refreshScreenCache = () => screenCache.refresh() export const clearScreenCache = () => screenCache.clear()