鸿蒙HarmonyOSArkUI(eTS)组件间通信涉及组件属性与显示、父子组件间通信、祖孙组件间通信、不相干组件间通信等,而组件两两间通信也有单向与双向之分。通过学习HDC2021和官方文档,本系列以State、Link、Prop、Provide与Consume、StorageLink等组件状态装饰器介绍组件间通信方式。 本次介绍:AppStorage与StorageLink、StorageProp。 AppStorage相当于UI框架为应用程序的可变状态属性提供了一个中央数据库,UI框架提供相应的装饰器和接口,用于添加、读取、修改和删除应用程序的状态属性,并通过StorageLink、StorageProp装饰器等在应用程序与AppStorage间同步数据,数据的更改会导致绑定该数据的UI组件重新渲染。程序启动时创建AppStorage单例对象,应用程序退出时销毁该对象。 组件的状态变量通过使用StorageLink装饰器与AppStorage建立双向数据绑定,该变量使用AppStorage中的值进行初始化。当AppStorage中的值变化时,使用该AppStorage的key的组件状态变量均同步变化。当不相干组件间通信时,相当于通过AppStorage中转达到组件间通信效果。使用StorageProp装饰器与AppStorage建立的是单向数据绑定,AppStorage中的属性值的更改会导致绑定的UI组件进行状态更新。 示例代码:AppStorage。SetOrCreate(myNum,0)EntryComponentstructIndex{build(){Column(){Text(父组件)。fontSize(50)。fontWeight(FontWeight。Bold)。margin({top:30})subIndex1()subIndex2()subIndex3()subIndex4()}。width(100)。height(100)。backgroundColor(Color。Pink)}}子组件1ComponentstructsubIndex1{StorageLink(myNum)sonVal:numberAppStorage。Getnumber(myNum)build(){Column(){Text(StorageLink子组件1:{this。sonVal})。fontSize(20)。margin({top:30})。width(90)。textAlign(TextAlign。Center)Row(){Button(加1)。width(100)。onClick((){this。sonVal})。margin({right:20})Button(减1)。width(100)。onClick((){this。sonVal})}}。backgroundColor(Color。Orange)。margin({bottom:20})}}子组件2ComponentstructsubIndex2{StorageLink(myNum)sonVal:numberAppStorage。Getnumber(myNum)build(){Column(){Text(StorageLink子组件2:{this。sonVal})。fontSize(20)。margin({top:30})。width(90)。textAlign(TextAlign。Center)Row(){Button(加1)。width(100)。onClick((){this。sonVal})。margin({right:20})Button(减1)。width(100)。onClick((){this。sonVal})}}。backgroundColor(Color。Orange)。margin({bottom:20})}}子组件3ComponentstructsubIndex3{StorageProp(myNum)sonVal:numberAppStorage。Getnumber(myNum)build(){Column(){Text(StorageProp子组件3:{this。sonVal})。fontSize(20)。margin({top:30})。width(90)。textAlign(TextAlign。Center)Row(){Button(加1)。width(100)。onClick((){this。sonVal})。margin({right:20})Button(减1)。width(100)。onClick((){this。sonVal})}}。backgroundColor(Color。Brown)。margin({bottom:20})}}子组件4ComponentstructsubIndex4{StorageLink(myNum)sonVal:numberAppStorage。Getnumber(myNum)build(){Column(){Text(测试接口子组件:{this。sonVal})。fontSize(20)。margin({top:30})。width(90)。textAlign(TextAlign。Center)Row(){Button(乘2)。width(100)。onClick((){this。sonValAppStorage。Getnumber(myNum)2})。margin({right:20})Button(置0)。width(100)。onClick((){AppStorage。Set(myNum,0)})}}。backgroundColor(Color。Green)}} 上例中程序启动时,创建一个键为myNum、值为0的AppStorage,UI中子组件共4个,其中前2个组件的状态变量用StorageLink装饰,与AppStorage双向数据绑定,第3个组件的状态变量用StorageProp装饰,与AppStorage单向数据绑定,第4个组件测试Set、Get等接口。