目录

@Trace: Observing Class Property Changes

@Trace is a property decorator used in state management V2. @ObservedV2 and @Trace are used together to decorate classes and class properties, enhancing the observation capability for decorated classes and properties. That is, they can recursively observe changes in property values of nested objects and trigger automatic UI refresh. They are applicable to scenarios where precise observation and management of class property changes are required.

For details, see @ObservedV2 and @Trace Decorators: Observing Class Property Changes.

This decorator is supported since API version 12.

@Trace

const Trace: PropertyDecorator

Declares an observable property. @Trace must be used together with @ObservedV2 and takes effect only in classes decorated with @ObservedV2.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 12.

Widget capability: This API can be used in ArkTS widgets since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example:

@ObservedV2
class Son {
  // Use @Trace to mark the property to be observed. When the property changes, UI refresh is triggered.
  @Trace age: number = 100;
}

class Father {
  son: Son = new Son();
}

@Entry
@ComponentV2
struct Index {
  father: Father = new Father();

  build() {
    Column() {
      Text(`${this.father.son.age}`)
      // After a click is made, the value of age increases by 1. The UI is automatically refreshed due to the @Trace decorator.
        .onClick(() => {
          this.father.son.age++;
        })
    }
  }
}