前言AppStorage是 HarmonyOS 的全局状态存储在整个应用的所有组件间共享数据。在「猫猫大作战」中AppStorage 用于存储登录状态、最高分、游戏设置等跨页面共享的全局数据。一、AppStorage 基础// 设置全局值AppStorage.setOrCreate(highScore,5000);AppStorage.setOrCreate(playerName,玩家小明);AppStorage.setOrCreate(soundEnabled,true);// 读取全局值consthighScoreAppStorage.getnumber(highScore);// 5000constplayerNameAppStorage.getstring(playerName);// 玩家小明constsoundOnAppStorage.getboolean(soundEnabled);// true二、在组件中使用// 方式 1StorageLink双向绑定EntryComponentstruct GameApp{StorageLink(highScore)highScore:number0;StorageLink(soundEnabled)soundEnabled:booleantrue;build(){Column(){Text(最高分:${this.highScore})Toggle({type:ToggleType.Switch,isOn:this.soundEnabled}).onChange((val){this.soundEnabledval;})}}}// 方式 2StorageProp单向只读Componentstruct ScoreDisplay{StorageProp(highScore)highScore:number0;}三、装饰器对比装饰器数据流修改效果场景StorageLink双向绑定组件修改 → AppStorage 更新设置页面StorageProp单向只读组件可读不可写展示页面四、游戏中的应用// 游戏结束时保存最高分endGame(){constcurrentHighAppStorage.getnumber(highScore)??0;if(this.scorecurrentHigh){AppStorage.setOrCreate(highScore,this.score);this.isNewHightrue;}}// 设置页面读写StorageLink(soundEnabled)soundEnabled:booleantrue;StorageLink(vibrateEnabled)vibrateEnabled:booleantrue;StorageLink(reminderHour)reminderHour:number20;五、AppStorage 与 Preferences 的关系特性AppStoragePreferences共享范围内存全局持久化文件应用重启数据丢失数据保留访问速度极快内存快文件 I/O使用场景运行时共享持久化设置提示AppStorage 在应用关闭后丢失。如果需要持久化在aboutToDisappear中将 AppStorage 数据写入 Preferences。六、最佳实践运行时共享用 AppStorage持久化用 PreferencesStorageLink双向绑定适合设置项StorageProp只读适合展示项应用退出前持久化将重要数据写入 PreferencesaboutToDisappear(){constprefspreferences.getPreferences(getContext()asContext,game_prefs);prefs.then(store{store.put(highScore,AppStorage.getnumber(highScore)??0);store.put(soundEnabled,AppStorage.getboolean(soundEnabled)??true);store.flush();});}总结AppStorage 是组件间共享全局状态的内存方案通过StorageLink/StorageProp绑定到 UI。核心要点setOrCreate写入、get读取、StorageLink双向绑定、 应用退出时持久化到 Preferences。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源AppStorage 官方文档Preferences 持久化第 139 篇KV Store第 141 篇fileIo