鸿蒙 UIAbility组件与UI的数据同步和窗口关闭
使用 EventHub 进行数据通信
根据 Stage 模型概念图 UIAbility
先于 ArkUI Page
创建
所以,事件要先 .on
订阅 再 emit
发布
假如现在有页面 Page1 和他的 UIAbility
// src/main/ets/page1ability/Page1Ability.ets
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {//通过EventHub对象在UIAbility和它加载的某个页面间共享数据let ctx = this.contextlet hub = ctx.eventHub //事件集中器对象//UIAbility监听事件集市中的事件,读取携带的数据hub.on('OnPage1Ability', (data:string)=>{console.log('--UIAbility监听到页面发布的事件,其中传来数据:', JSON.stringify(data))})}
// src/main/ets/pages/Page1.ets
@Entry
@Component
struct Page1 {@State message: string = 'Page1';build() {Button('在事件集中器对象中发射一个事件').onClick(_=>{let ctx = getContext()let hub = ctx.eventHub //事件集中器对象//页面发布一个事件,并携带数据hub.emit('OnPage1Ability','Page1_Send_Msg')})}
}
先在 UIAbility 订阅 on ,再在 Page1 发布事件 emit,不要反过来,不然 UIAbility 事件发布后 UI 页面还没生成,拿什么订阅
使用 AppStorage 进行数据同步
应用级别的数据同步
在 HarmonyOS 应用中,最快初始化或使用 AppStorage 的位置通常是应用的入口组件(@Entry 装饰的组件),或是通过单独的状态管理文件集中声明全局状态。
假如我现在随便找个 UIAbility 加它的 UI 来举例吧
忘了,介绍 2 个装饰器先
以下是 AppStorage 的应用全局 UI 状态存储装饰器对比表格,基于 HarmonyOS 官方文档梳理:
特性 | @StorageProp | @StorageLink |
---|---|---|
装饰器参数 | key: string (常量字符串,必填) | key: string (常量字符串,必填) |
同步类型 | 单向(AppStorage→ 组件) | 双向(AppStorage↔ 组件) |
数据流方向 | AppStorage 的值覆盖组件本地值 | 组件修改同步回 AppStorage,AppStorage 变更同步到所有绑定组件 |
允许的数据类型 | 基础类型、对象、数组(不支持 any、undefined/null) | 与@StorageProp 相同 |
初始值要求 | 必须指定,若 AppStorage 无对应属性则创建并存储 | 必须指定,规则同@StorageProp |
本地修改行为 | 允许本地修改,但会被 AppStorage 更新覆盖 | 本地修改直接触发 AppStorage 全局更新 |
适用场景 | 全局只读配置(如主题色、语言)、设备信息 | 需双向交互的状态(如用户登录态、购物车商品数) |
// src/main/ets/page1ability/Page1Ability.ets
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {AppStorage.setOrCreate('cartCount', 99)AppStorage.setOrCreate('themeColor', '#ff13c613') // 确保全局存在}
// src/main/ets/pages/Page1.ets
import { common } from '@kit.AbilityKit'
@Entry
@Component
struct Page1 {@State message: string = 'Page1';@StorageProp('themeColor') color: string = '#ff13c613' // 全局主题色@StorageLink('cartCount') count: number = 0 // 购物车商品数build() {Column({space:10}) {Text('当前主题色').fontColor(this.color)Button(`商品数量:${this.count}`).onClick(() => this.count++) // 可以修改}}
}
使用 LocalStorage 进行数据同步
UIAbility 级别的数据同步
介绍 2 个装饰器先
对比项 | @LocalStorageProp | @LocalStorageLink |
---|---|---|
同步方向 | 单向(LocalStorage→ 组件) | 双向(LocalStorage↔ 组件) |
初始值要求 | 必须指定,用于初始化 LocalStorage 属性(若不存在) | 同左 |
本地修改影响 | 本地修改不触发回传,会被 AppStorage 更新覆盖 | 本地修改自动同步至 LocalStorage,触发全局刷新 |
适用场景 | 只读全局配置(如主题色、语言) | 动态交互状态(如用户输入、表单数据) |
例子不写了,看官网吧
关闭窗口
import { common } from '@kit.AbilityKit'@Entry
@Component
struct Page1 {@State message: string = 'Page1';build() {Column({space:10}) {Text(this.message).fontSize(30)Button('关闭当前窗口').onClick(_=>{let ctx = getContext( ) as common.UIAbilityContext //得到页面所在UIAbility对应的UIAbilityContextctx.terminateSelf()})Button('关闭当前应用的所有窗口,即退出程序').onClick(_=>{let ctx = getContext( ) as common.UIAbilityContextlet appCtx = ctx.getApplicationContext()appCtx.killAllProcesses()})}}
}