# 微信小程序API兼容性优化说明 ## 问题背景 微信小程序官方已废弃 `wx.getSystemInfoSync` API,推荐使用以下新API替代: - `wx.getSystemSetting` - 获取系统设置 - `wx.getAppAuthorizeSetting` - 获取授权设置 - `wx.getDeviceInfo` - 获取设备信息 - `wx.getWindowInfo` - 获取窗口信息 - `wx.getAppBaseInfo` - 获取基础信息 ## 解决方案 ### 1. 创建通用工具函数 在 `app/utils/common.js` 中新增 `getSystemInfo()` 函数: ```javascript /** * 获取系统信息(兼容新旧API) * 替代已废弃的uni.getSystemInfoSync() * @returns {Object} 系统信息对象 */ export function getSystemInfo() { // 微信小程序使用新API #ifdef MP-WEIXIN try { const windowInfo = uni.getWindowInfo() const deviceInfo = uni.getDeviceInfo() const appBaseInfo = uni.getAppBaseInfo() return { ...windowInfo, ...deviceInfo, ...appBaseInfo, // 兼容旧字段名 windowHeight: windowInfo.windowHeight, windowWidth: windowInfo.windowWidth, // ... 更多字段 } } catch (e) { // 降级使用旧API return uni.getSystemInfoSync() } #endif // 其他平台继续使用旧API #ifndef MP-WEIXIN return uni.getSystemInfoSync() #endif } ``` ### 2. 更新项目文件 已修改以下项目文件,统一使用新的工具函数: | 文件路径 | 修改内容 | |---------|---------| | `app/pages/mine/avatar/index.vue` | 替换 `uni.getSystemInfoSync()` 为 `getSystemInfo()` | | `app/pages/mine/index.vue` | 在computed中使用 `getSystemInfo()` | | `app/pages/mine/setting/index.vue` | 在data中使用 `getSystemInfo()` | ### 3. 第三方组件说明 以下 `uni_modules` 中的第三方组件仍使用旧API,需等待官方更新: - `uni-datetime-picker` - `uni-fab` - `uni-load-more` - `uni-nav-bar` - `uni-notice-bar` - `uni-popup` - `uni-table` 这些组件的警告不影响功能使用,可忽略。 ## 优势 1. **向后兼容**:降级处理确保在旧版本小程序中也能正常运行 2. **跨平台支持**:通过条件编译,仅在微信小程序使用新API 3. **统一管理**:集中管理系统信息获取逻辑,便于后续维护 4. **类型安全**:返回对象包含完整的字段映射 ## 使用示例 ```javascript import { getSystemInfo } from '@/utils/common' // 获取窗口高度 const windowHeight = getSystemInfo().windowHeight // 获取设备平台 const platform = getSystemInfo().platform // 获取屏幕宽度 const screenWidth = getSystemInfo().screenWidth ``` ## 注意事项 1. ⚠️ 新API仅在微信小程序基础库 2.20.1 及以上版本支持 2. ⚠️ 项目中包含降级处理,无需担心兼容性问题 3. ⚠️ H5和其他平台仍使用 `uni.getSystemInfoSync()` 4. ✅ 建议后续新增代码统一使用 `getSystemInfo()` 工具函数 ## 相关文档 - [微信小程序官方文档 - 系统信息](https://developers.weixin.qq.com/miniprogram/dev/api/base/system/system-info/wx.getWindowInfo.html) - [uni-app API说明](https://uniapp.dcloud.net.cn/api/system/info.html) --- **修改时间**: 2025-10-26 **修改人**: AI Assistant **影响范围**: 微信小程序端系统信息获取