鸿蒙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。如需转载,请注明出处。

相关推荐
ai安歌4 小时前
鸿蒙PC:Qt适配OpenHarmony实战【取色间】:RGB 滑动调整、HEX 展示和颜色预览
qt·华为·harmonyos
lqj_本人5 小时前
鸿蒙electron跨端框架PC想法卡片实战:把零散灵感做成能继续展开的卡片流
华为·electron·harmonyos
专注前端30年6 小时前
2025-2026 大厂 Vue2Vue3 高频面试题 Top100
百度·华为·大厂面试题·阿里·前端vue2/3
lqj_本人8 小时前
鸿蒙electron跨端框架PC浮签实战:做一面轻巧但能回找的桌面便签墙
华为·harmonyos
ai安歌8 小时前
鸿蒙PC:Qt适配OpenHarmony实战【人名录】:单机联系人卡片,不读系统通讯录也能演示详情联动
数据库·qt·harmonyos
lqj_本人9 小时前
鸿蒙electron跨端框架PC简序实战:把轻任务、优先级和截止时间塞进一张桌面清单
华为·harmonyos
想你依然心痛10 小时前
HarmonyOS 6 悬浮导航 + 沉浸光感:打造鸿蒙智能体驱动的沉浸式智能家居控制中枢
华为·ar·智能家居·harmonyos·智能体
lqj_本人10 小时前
鸿蒙PC:Qt适配OpenHarmony实战【花账】:从一笔支出开始,做一个本地记账小应用
数据库·qt·harmonyos
递归40410 小时前
ofdkit-harmony 0.2.0 发布:鸿蒙原生 OFD 阅读库,已上架 ohpm
开源·harmonyos·arkts·ofd·ohpm
nashane11 小时前
HarmonyOS 6学习:SoundPool音频防抖与Web长截图时序重构
学习·音视频·harmonyos·harmonyos 5