一、基础状态管理装饰器
0. 组件V2饰器
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@ComponentV2 | 定义自定义组件,V2 版本强化了组件生命周期和性能优化。 | @ComponentV2 struct MyComponent { ... } |
1. 组件内部状态
| 装饰器 | 作用 | 示例代码 | |
|---|---|---|---|
@Local | 声明组件内部可变状态,替代旧版 @State,更轻量。 | @Local count: number = 0; | |
@Computed | 声明计算属性,自动根据依赖状态更新。 | @Computed get total() { return this.price * this.quantity; } |
2. 组件外部输入
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@Param | 接收父组件传递的参数(单向输入),替代旧版 @Prop。 | @Param title: string = '默认标题'; |
@Once | @Once使用在期望变量仅初始化时同步数据源一次,之后不再继续同步变化的场景。 | @Param @Once onceParam: string = "onceParam" |
二、组件通信与数据流
1. 父子组件交互
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@Event | 定义组件输出事件(子组件向父组件传递数据)。 | @Event onUpdate: (value: number) => void; |
2. 跨组件层级同步
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@Provider/@Consumer | 实现跨组件层级的双向数据同步(替代旧版 @Provide/@Consume)。 | @Provider theme: string = 'dark'; @Consumer theme: string; |
三、类与属性增强
1. 类装饰器
|
| @ObservedV2 | 标记类为可观察对象,属性变化触发 UI 更新(需配合 @Trace 使用)。 | @ObservedV2 class User { @Trace name: string = 'Alice'; } |
2. 属性类型规范
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@Type | 显式声明类属性的类型,增强代码可读性和类型检查。 | @Type(String) name: string = 'Tom'; |
四、状态监听与计算
| 装饰器 | 作用 | 示例代码 |
|---|---|---|
@Monitor | 监听状态变量的修改,执行副作用逻辑(如日志、联动更新)。 | @Monitor('count') onCountChange(newVal) { console.log(newVal); } |
综合示例场景
场景:实现一个用户信息组件
typescript
复制
// 定义可观测的用户类
@ObservedV2
class User {
@Trace name: string = 'Alice';
@Trace age: number = 25;
}
// 父组件
@ComponentV2
struct ParentComponent {
@Local private user: User = new User(); // 内部状态
@Provider sharedData: string = '全局配置'; // 跨组件共享
build() {
Column() {
ChildComponent({ user: this.user }) // 传递用户对象
Text(`年龄:${this.user.age}`)
}
}
}
// 子组件
@ComponentV2
struct ChildComponent {
@Param user: User; // 接收父组件参数
@Consumer sharedData: string; // 消费共享数据
@Monitor('user.age') // 监听年龄变化
onAgeChange(newAge: number) {
console.log(`年龄更新为:${newAge}`);
}
@Computed // 计算属性
get displayInfo() {
return `${this.user.name} (${this.sharedData})`;
}
build() {
Column() {
Text(this.displayInfo) // 显示计算属性
Button("修改年龄").onClick(() => this.user.age++)
}
}
}
核心差异总结(V2 vs V1)
-
更细粒度的状态管理
@ObservedV2+@Trace替代旧版@Observed,支持对象属性级监听。@Local替代@State,明确区分组件内部状态。
-
类型系统增强
@Type显式声明属性类型,减少运行时错误。
-
性能优化
@ComponentV2优化渲染机制,减少不必要的 UI 更新。
-
双向同步简化
@Provider/@Consumer替代@Provide/@Consume,默认支持双向绑定。
快速上手建议
-
优先使用
@Local管理组件内部状态。 -
跨组件通信:
- 简单数据用
@Param+@Event; - 复杂对象用
@ObservedV2+@Trace。
- 简单数据用
-
需要持久化或全局状态时,结合
@Provider/@Consumer。 -
使用
@Computed减少重复计算,提升性能。