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

相关推荐
御承扬3 小时前
鸿蒙NDK UI之文本自定义样式
ui·华为·harmonyos·鸿蒙ndk ui
前端不太难3 小时前
HarmonyOS 游戏上线前必做的 7 类极端场景测试
游戏·状态模式·harmonyos
大雷神3 小时前
HarmonyOS智慧农业管理应用开发教程--高高种地--第29篇:数据管理与备份
华为·harmonyos
讯方洋哥4 小时前
HarmonyOS App开发——关系型数据库应用App开发
数据库·harmonyos
巴德鸟5 小时前
华为手机鸿蒙4回退到鸿蒙3到鸿蒙2再回退到EMUI11 最后关闭系统更新
华为·智能手机·harmonyos·降级·升级·回退·emui
一起养小猫5 小时前
Flutter for OpenHarmony 实战_魔方应用UI设计与交互优化
flutter·ui·交互·harmonyos
一只大侠的侠5 小时前
Flutter开源鸿蒙跨平台训练营 Day7Flutter+ArkTS双方案实现轮播图+搜索框+导航组件
flutter·开源·harmonyos
那就回到过去5 小时前
VRRP协议
网络·华为·智能路由器·ensp·vrrp协议·网络hcip
相思难忘成疾6 小时前
通向HCIP之路:第四步:边界网关路由协议—BGP(概念、配置、特点、常见问题及其解决方案)
网络·华为·hcip
一只大侠的侠6 小时前
Flutter开源鸿蒙跨平台训练营 Day9分类数据的获取与渲染实现
flutter·开源·harmonyos