Harmonyos 状态管理@ObservedV2装饰器和@Trace装饰器

408 阅读1分钟

“本文正在参加华为鸿蒙有奖征文征文活动”

  • @ObservedV2装饰器与@Trace装饰器用于装饰类以及类中的属性,使得被装饰的类和属性具有深度观测的能力
  • @ObservedV2装饰器与@Trace装饰器必须在@ComponentV2使用
  • 主要作用就是可以修改类属性

先创建一个类

@ObservedV2
class Son {
  @Trace age: number = 0
}
class Father {
  son: Son = new Son()
}
@Preview
@ComponentV2
struct ObservedV2AndTraceComp {
  pathStack: NavPathStack = new NavPathStack()
  father: Father = new Father()
  gs: GrandSon = new GrandSon()



  build() {
    NavDestination() {
      Column() {
        Text('点我点我\n' + this.gs.age)
          .onClick(() => {
            this.gs.age++
          })
      }
    }.title(this.pathStack.getParamByName(RouterConstants.ObservedV2AndTraceComp) + '')
    
  }
}

image.png

在继承类中使用@Trace装饰的属性具有被观测变化的能力

/** 在继承类中使用@Trace装饰的属性具有被观测变化的能力。 */
class GrandSon extends Son {
}