鸿蒙HarmonyOS最新的组件间通信的装饰器与状态组件详解

本文系统梳理了鸿蒙(HarmonyOS)ArkUI中组件间通信相关的装饰器及状态组件的使用方法,重点介绍V2新特性,适合开发者查阅与实践。

概述

鸿蒙系统(HarmonyOS)ArkUI提供了丰富的装饰器和状态组件,用于简化组件之间的数据通信和状态管理。这些装饰器和组件在V1版本的基础上继续优化,并在V2版本中引入了新的特性,使得开发者能够更高效地构建复杂的应用程序。本文将详细介绍这些装饰器和状态组件,帮助开发者更好地理解和应用它们。


1. @ComponentV2 装饰器

  • 用于自定义组件,启用V2状态管理能力。
  • 仅能与V2系列装饰器(如@Local、@Param、@Once、@Event、@Provider、@Consumer等)配合使用。
  • 不能与@Component混用。

示例:

ts 复制代码
@ComponentV2
struct MyComponent {
  build() {
    // ...
  }
}

2. @Local 装饰器(组件内部状态)

  • 仅能在@ComponentV2中使用。
  • 表示组件内部状态,变量必须本地初始化,不能被外部初始化。
  • 支持number、string、boolean、Object、class、Array、Set、Map、Date等类型。
  • 变量变化会自动刷新绑定的UI。
  • 对象属性的深度观测需配合@ObservedV2和@Trace。

示例:

ts 复制代码
@ComponentV2
struct Example {
  @Local count: number = 0;
  @Local message: string = "Hello";
  build() {
    Column() {
      Text(`${this.count}`)
      Button("change Local").onClick(() => {
        this.count++;
      })
    }
  }
}

3. @State 装饰器(V1组件内状态)

  • 仅能在@Component中使用。
  • 变量可本地初始化,也可由父组件初始化。
  • 变量变化会自动刷新绑定的UI。
  • 支持number、string、boolean、Object、class、Array、Date、Map、Set等类型。
  • 嵌套对象属性变化观测有限。

示例:

ts 复制代码
@Component
struct Example {
  @State count: number = 0;
  build() {
    Button(`click times: ${this.count}`).onClick(() => {
      this.count += 1;
    })
  }
}

4. @Provider/@Consumer 装饰器(V2跨组件层级双向同步)

  • 仅能在@ComponentV2中使用。
  • @Provider为数据提供方,@Consumer为数据消费方,通过aliasName(或属性名)建立绑定。
  • 支持number、string、boolean、class、Array、Date、Map、Set等类型。
  • 建立后可实现父子组件间的双向同步。

示例:

ts 复制代码
@Entry
@ComponentV2
struct Parent {
  @Provider() str: string = 'hello';
  build() {
    Column() {
      Button(this.str).onClick(() => { this.str += '0'; })
      Child()
    }
  }
}
@ComponentV2
struct Child {
  @Consumer() str: string; // 注意:@Consumer变量不需要初始化,因为其值会从Provider处获取
  build() {
    Button(this.str).onClick(() => { this.str += '0'; })
  }
}

5. @ObservedV2/@Trace 装饰器(V2类属性深度观测)

  • @ObservedV2装饰class,@Trace装饰class属性。
  • 需配合使用,支持嵌套对象属性的深度观测。
  • 仅V2支持,适合复杂数据结构的UI联动。

示例:

ts 复制代码
@ObservedV2
class Info {
  @Trace name: string;
  @Trace region: string;
  constructor(name: string, region: string) {
    this.name = name;
    this.region = region;
  }
}
@ComponentV2
struct Example {
  @Local info: Info = new Info('Tom', 'North');
  build() {
    Text(this.info.name)
    Button('change').onClick(() => { this.info.name = 'Jack'; })
  }
}

6. @Event 装饰器(V2组件输出)

  • 仅能在@ComponentV2中使用。
  • 用于装饰回调方法,实现子组件向父组件传递事件。
  • 常与@Param配合,实现数据的双向同步。

示例:

ts 复制代码
@ComponentV2
struct Child {
  @Param index: number = 0;
  @Event changeIndex: (val: number) => void;
  build() {
    Button('change').onClick(() => {
      this.changeIndex(20);
    })
  }
}
@Entry
@ComponentV2
struct Parent {
  @Local index: number = 0;
  build() {
    Child({
      index: this.index,
      changeIndex: (val: number) => { this.index = val; }
    })
  }
}

7. @Monitor 装饰器(V2状态变量深度监听)

  • 仅能在@ComponentV2或@ObservedV2装饰的类中使用。
  • 可监听多个属性的变化,支持深度监听。
  • 回调参数可获取变化前后的值。

示例:

ts 复制代码
@ComponentV2
struct Example {
  @Local message: string = "Hello";
  @Monitor("message")
  onMessageChange(monitor: IMonitor) {
    console.log(`message changed from ${monitor.prev} to ${monitor.cur}`);
  }
}

8. @Watch 装饰器(V1状态变量监听)

  • 仅能在@Component中使用。
  • 用于监听@State、@Prop、@Link等装饰的变量变化。
  • 回调函数名作为参数。

示例:

ts 复制代码
@Component
struct Example {
  @State count: number = 0;
  @Watch('count')
  onCountChange(count: number, prevCount: number) {
    console.log(`count changed from ${prevCount} to ${count}`);
  }
}

总结

鸿蒙系统ArkUI通过引入各种装饰器和状态组件,极大地方便了开发者进行组件间的数据通信和状态管理。本文详细介绍了这些装饰器和组件的使用方法,特别是V2版本的新特性。开发者可以根据实际需求选择合适的装饰器和状态组件来构建高效、可维护的应用程序。


参考

作者

csdn猫哥,blog.csdn.net/yyz_1987。如需转载,请注明出处。

相关推荐
阿健君44 分钟前
Harmony NDK 开发
harmonyos
UnicornDev2 小时前
【HarmonyOS 6】鸿蒙原生应用智能体接入
华为·harmonyos·arkts·鸿蒙·鸿蒙系统
梦想不只是梦与想2 小时前
鸿蒙中 PhotoViewPicker:选择图片或视频
harmonyos·鸿蒙·photoviewpicker
独特的螺狮粉3 小时前
云隙一言:鸿蒙Flutter框架 实现的随机名言应用
开发语言·flutter·华为·架构·开源·harmonyos
Utopia^5 小时前
鸿蒙flutter第三方库适配 - 图片拼图工具
flutter·华为·harmonyos
星释5 小时前
鸿蒙Flutter实战:29.优先使用联合插件开发鸿蒙化插件
flutter·华为·harmonyos·鸿蒙
特立独行的猫a5 小时前
OpenHarmony平台移植 gifsicle:C/C++ 三方库适配实践(Lycium / tpc_c_cplusplus)
c语言·c++·harmonyos·openharmony·三方库适配·lycium
不爱吃糖的程序媛5 小时前
鸿蒙三方库适配读懂 `README_zh.md`:中文适配说明里每段在说什么?
华为·harmonyos
见山是山-见水是水6 小时前
鸿蒙flutter第三方库适配 - 文件加密工具
flutter·华为·harmonyos
key_3_feng7 小时前
HarmonyOS 6.0 健康食谱应用开发方案
华为·harmonyos