鸿蒙Next状态管理装饰器V2 @ObservedV2@Trace@Local
2025-06-27 22:37:45
115次阅读
0个评论
本文先记录@ObservedV2装饰器 @Trace装饰器 @Local装饰器 当我们的数据结构有嵌套对象时,当只有嵌套对象属性发生变化,这时不能触发View刷新,看一下效果图和代码:
@Observed
class Child{
name:string='child'
}
@Observed
class Father{
name:string='father'
child:Child=new Child();
}
@Entry
@Component
struct test{
@State father:Father = new Father()
build() {
Stack(){
Column({space:30}){
Text(this.father.name).fontSize(30).fontColor(Color.Black)
Text(this.father.child.name).fontSize(30).fontColor(Color.Gray)
Row(){
Button('改变child属性').onClick(()=>{
//只有嵌套类对对象属性变化不能被监听到
this.father.child.name='child2'
})
Button('改变father属性').onClick(()=>{
this.father.name='father2'
})
}
}
}.alignContent(Alignment.Center)
.width('100%')
.height('100%')
}
}
为了解决这种需求,需要引入V2所属装饰器,为了增强状态管理框架对类对象中属性的观测能力,开发者可以使用@ObservedV2装饰器和@Trace装饰器装饰类以及类中的属性。 概述 @ObservedV2装饰器与@Trace装饰器用于装饰类以及类中的属性,使得被装饰的类和属性具有深度观测的能力: @ObservedV2装饰器与@Trace装饰器需要配合使用,单独使用@ObservedV2装饰器或@Trace装饰器没有任何作用。 被@Trace装饰器装饰的属性property变化时,仅会通知property关联的组件进行刷新。 在嵌套类中,嵌套类中的属性property被@Trace装饰且嵌套类被@ObservedV2装饰时,才具有触发UI刷新的能力。 在继承类中,父类或子类中的属性property被@Trace装饰且该property所在类被@ObservedV2装饰时,才具有触发UI刷新的能力。 未被@Trace装饰的属性用在UI中无法感知到变化,也无法触发UI刷新。 @ObservedV2的类实例目前不支持使用JSON.stringify进行序列化。
@ObservedV2
class Child{
@Trace name:string='child'
}
@ObservedV2
class Father{
@Trace name:string='father'
child:Child=new Child();
}
@Entry
@ComponentV2
struct test2{
father:Father = new Father()
@Local message: string = "Hello";
build() {
Stack(){
Column({space:10}){
Text(this.message).fontSize(30)
Text(this.father.name).fontSize(30)
Text(this.father.child.name).fontSize(30)
Row(){
Button('locak修饰').onClick(()=>{
this.message='world'
})
Button('改变child属性').onClick(()=>{
this.father.child.name='child2'
})
Button('改变father属性').onClick(()=>{
this.father.name='father2'
})
}
}
}.alignContent(Alignment.Center)
.width('100%')
.height('100%')
}
}
00
- 0回答
- 0粉丝
- 0关注
相关话题
- 鸿蒙Next状态管理装饰器V2 @Provider @Consumer
- 【HarmonyOS Next】鸿蒙状态管理V2装饰器详解
- 鸿蒙Next状态管理装饰器V2 @Param@Once@Event
- HarmonyOS Next V2 状态管理@ObservedV2基本使用
- 【HarmonyOS Next】鸿蒙状态管理装饰器V1和V2混用方案
- 鸿蒙-状态管理V2
- 状态管理V2
- HarmonyOS Next V2 状态管理实战
- HarmonyOS Next V2 @Local和@Param
- 鸿蒙开发:刷新库V2装饰器适配
- 鸿蒙NEXT-状态管理V1和状态管理V2的差别
- 鸿蒙开发:V2版本装饰器之@Monitor装饰器
- 鸿蒙Next组件状态管理装饰器V1
- 鸿蒙开发:V2版本装饰器@Once
- 鸿蒙-状态管理V2其他方法