openharmony 鸿蒙 ts-state-management-watch-monitor

2026-08-25 浏览 (1)

State Variable Change Listening

The state variable listening module provides the capability to observe changes in state variables.

This document is solely for API reference. For details about the usage guidelines and constraints, see the development guide of each API.

NOTE

The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Watch

Watch: (value: string) => PropertyDecorator

The @Watch decorator is used to listen for state variable changes in state management V1. For details about how to use @Watch, see @Watch Decorator: Getting Notified of State Variable Changes.

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuestringYesName of the callback function used for listening. The value is specified by you.

Return value

TypeDescription
PropertyDecoratorProperty decorator. You do not need to concern yourself with this return value.

Example

@Entry
@Component
struct Index {
  @State @Watch('onChange') num: number = 0; // The @Watch input parameter is the function name.

  onChange() {
    console.info(`num change to ${this.num}`);
  }

  build() {
    Column() {
      Text(`num is: ${this.num}`)
        .onClick(() => {
          this.num++; // This triggers the onChange callback.
        })
    }
  }
}

Monitor12+

Monitor: MonitorDecorator

The @Monitor decorator is used to listen for state variable changes in state management V2. For details about how to use @Monitor, see @Monitor Decorator: Listening for Value Changes of the State Variables.

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

MonitorDecorator12+

type MonitorDecorator = (value: string, ...args: string[]) => MethodDecorator

Represents the actual type of the @Monitor decorator.

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
valuestringYesVariable path name used for listening, specified by you. When only one string is passed, this is the parameter type.
...argsstring[]NoArray of variable path names used for listening, specified by you. When multiple strings are passed, this is the parameter type.

Return value

TypeDescription
MethodDecoratorMethod decorator. You do not need to concern yourself with this return value.

Example

@ObservedV2
class Info {
  @Trace name: string = 'Tom';
  @Trace age: number = 25;
  @Trace height: number = 175;

  // Listen for one variable.
  @Monitor('name')
  onNameChange() {
    console.info(`name change to ${this.name}`);
  }

  // Listen for multiple variables.
  @Monitor('age','height')
  onRecordChange(monitor: IMonitor) {
    monitor.dirty.forEach((path: string) => {
      console.info(`${path} change from ${monitor.value(path)?.before} to ${monitor.value(path)?.now}`);
    })
  }
}

@Entry
@ComponentV2
struct Index {
  @Local info: Info = new Info();

  build() {
    Column() {
      Text(`info.name: ${this.info.name}`)
        .onClick(() => {
          this.info.name = 'Bob'; // Output log: name change to Bob
        })
      Text(`info.age: ${this.info.age}, info.height: ${this.info.height}`)
        .onClick(() => {
          this.info.age++; // Output log: age change from 25 to 26
          this.info.height++; // Output log: height change from 175 to 176
        })
    }
  }
}

IMonitor12+

When the monitored variable changes, the state management framework will call the registered function and pass the change information of the IMonitor type.

Properties

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeRead-OnlyOptionalDescription
dirty12+Array<string>NoNoArray of changed paths.

value12+

value<T>(path?: string): IMonitorValue<T>|undefined

Obtains the change information for the specified path.

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
pathstringNoPath name of the monitored variable. If it is not specified, the first path in the dirty array is used by default.

Return value

TypeDescription
IMonitorValue<T> |undefinedPath and change information for the monitored variable.
T is the type of the monitored variable.
If the monitored path does not exist, undefined is returned.
If no path is specified, the information corresponding to the first path in the dirty array is returned by default.

Example

@ObservedV2
class Info {
  @Trace name: string = 'Tom';
  @Trace age: number = 25;
  @Trace height: number = 175;

  //Listen for one variable.
  @Monitor('name')
  onNameChange(monitor: IMonitor) {
    // If no path is specified for value, the first path in the dirty array is used by default.
    console.info(`path: ${monitor.value()?.path} change from ${monitor.value()?.before} to ${monitor.value()?.now}`);
  }

  // Listen for multiple variables.
  @Monitor('age','height')
  onRecordChange(monitor: IMonitor) {
    // If a path is specified for value, the change information for the specified path is returned.
    monitor.dirty.forEach((path: string) => {
      console.info(`path: ${path} change from ${monitor.value(path)?.before} to ${monitor.value(path)?.now}`);
    })
  }
}

@Entry
@ComponentV2
struct Index {
  @Local info: Info = new Info();

  build() {
    Column() {
      Text(`info.name: ${this.info.name}`)
        .onClick(() => {
          this.info.name = 'Bob'; // Output log: path: name change from Tom to Bob
        })
      Text(`info.age: ${this.info.age}, info.height: ${this.info.height}`)
        .onClick(() => {
          this.info.age++; // Output log: path: age change from 25 to 26
          this.info.height++; // Output log: path: height change from 175 to 176
        })
    }
  }
}

IMonitorValue<T>12+

Provides the specific change information for the monitored variable, obtained through the value API of IMonitor. T is the type of the variable.

Properties

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeRead-OnlyOptionalDescription
before12+TNoNoVariable value before change.
now12+TNoNoCurrent variable value.
path12+stringNoNoVariable path.

Example

@ObservedV2
class Info {
  @Trace name: string = 'Tom';
  @Monitor('name')
  onNameChange(monitor: IMonitor) {
    // The return value of value is of the IMonitorValue type, through which the variable change information can be obtained.
    console.info(`path: ${monitor.value()?.path} change from ${monitor.value()?.before} to ${monitor.value()?.now}`);
  }
}
@Entry
@ComponentV2
struct Index {
  @Local info: Info = new Info();
  build() {
    Column() {
      Text(`info.name: ${this.info.name}`)
        .onClick(() => {
          this.info.name = 'Bob'; // Output log: path: name change from Tom to Bob
        })
    }
  }
}

SyncMonitor23+

SyncMonitor: MonitorDecorator

The @SyncMonitor decorator is used to listen for state variable changes in state management V2. For details about how to use @SyncMonitor, see @SyncMonitor Decorator: Synchronous Listening for Value Changes of the State Variables.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

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

NameTypeDescription
SyncMonitorMonitorDecoratorAttribute decorator, which listens for the changes of state variables.

Error codes:

For details about the error codes, see State Management Error Codes.

IDError Message
130001The path is invalid.

Example

import { hilog } from '@kit.PerformanceAnalysisKit';

@ObservedV2
class Info {
  @Trace name: string = 'Tom';
  @Trace age: number = 25;
  @Trace height: number = 175;

  //Listen for one variable.
  @SyncMonitor('name')
  onNameChange() {
    hilog.info(0xFF00, 'testTag', '%{public}s', `name change to ${this.name}`);
  }

  // Listen for multiple variables.
  @SyncMonitor('age','height')
  onRecordChange(monitor: IMonitor) {
    monitor.dirty.forEach((path: string) => {
      hilog.info(0xFF00, 'testTag', '%{public}s',
        `${path} change from ${monitor.value(path)?.before} to ${monitor.value(path)?.now}`);
    })
  }
}

@Entry
@ComponentV2
struct Index {
  @Local info: Info = new Info();

  build() {
    Column() {
      Text(`info.name: ${this.info.name}`)
        .onClick(() => {
          this.info.name = 'Bob'; // Output log: name change to Bob
        })
      Text(`info.age: ${this.info.age}, info.height: ${this.info.height}`)
        .onClick(() => {
          this.info.age++; // Output log: age change from 25 to 26
          this.info.height++; // Output log: height change from 175 to 176
        })
    }
  }
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 ts-drawing-components-shape

openharmony 鸿蒙 ts-universal-attributes-sharp-clipping

openharmony 鸿蒙 ts-universal-attributes-toolbar

openharmony 鸿蒙 ts-container-lazyvgridlayout

openharmony 鸿蒙 ohos-arkui-advanced-FoldSplitContainer

openharmony 鸿蒙 ts-methods-calendarpicker-dialog

openharmony 鸿蒙 ts-uicommonevent

openharmony 鸿蒙 ts-basic-gestures-tapgesture

openharmony 鸿蒙 ohos-arkui-advanced-DialogV2

openharmony 鸿蒙 ts-components-canvas-canvas

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/nex7UZtU