# 14.7:@ObserverV2和@Trace
@ObserverV2 用来装饰 Class
,表明当前类可被观察,单独使用此装饰器无效,它只能和 @Trace 配合使用,@Trace 表示当前 Classs
的属性可被精确跟踪观察,其也只能在 @ObserverV2 装饰的 Class
内使用。
# 14.7.1:约束与限制
- @ObserverV2 必须和 @Trace 配合使用,单独使用均无效。
- @ObserverV2 仅能装饰
Class
,无法装饰自定义组件。 - @ObservedV2 的类实例目前不支持使用 JSON.stringify 进行序列化。
# 14.7.2:语法介绍
@ObserverV2 必须装饰 class
,它是和 @Trace 配对使用的,单独使用一方则无效,格式如下:
@ObservedV2
class class_name {
@Trace
attribute_name: attribute_type = this.attribute_value?
}
1
2
3
4
5
6
7
2
3
4
5
6
7
样例如下所示:
@ObservedV2
class User {
userID: string = ""
@Trace userName: string = "张三"
@Trace birthday: string = "2020-4-12"
}
1
2
3
4
5
6
2
3
4
5
6
User
使用 @ObservedV2 装饰,代表着当前类可被观察,属性 userName
和 birthday
被 @Trace 装饰,代表着它们有变更的时候,使用了这俩属性的组件都会触发UI更新。
# 14.7.3:简单样例
@ObserverV2 和 @Trace 的使用很简单,分别装饰 Class
和其属性即可,简单样例如下所示:
@ObservedV2 class Person { // Person使用@ObservedV2装饰器,表示该类是可被观察的
@Trace age: number = 30; // 属性age使用@Trace装饰,表示该属性都会被精确观察
}
@Entry
@ComponentV2
struct Index {
person: Person = new Person();
build() {
Column() {
Text(`${this.person.age}`)
.onClick(() => {
this.person.age++; // 当点击Text组件时,改变age时,Text组件会刷新
})
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
组件 Text
使用了 @ObserverdV2 装饰的状态属性 age
,当点击 Text
时 age
的值会累加则触发 UI 刷新,样例运行结果如下所示:
# 14.7.4:使用场景
在嵌套类中使用
@ObservedV2 class Son { @Trace age: number = 30; } class Father { son: Son = new Son(); } @Entry @ComponentV2 struct Index { father: Father = new Father(); build() { Column() { Text(`${this.father.son.age}`) .onClick(() => { this.father.son.age++; // 当点击Text组件时,改变age时,Text组件会刷新 }) .width("100%") .backgroundColor("#aabbcc") } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25Father
内声明了Son
实例,Text
使用了Father
内Son
的状态属性时,当点击发生时更新Son
的值会引发 UI 刷新。样例运行结果如下所示:在继承类中使用
@ObservedV2 class Father { @Trace name: string = "Tom"; } class Son extends Father { } @Entry @ComponentV2 struct Index { son: Son = new Son(); build() { Column() { Text(`${this.son.name}`) .onClick(() => { this.son.name = "Jack"; // 当点击改变name时,Text组件会刷新 }) .width("100%") .backgroundColor("#aabbcc") } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24子类
Son
继承了可观察类Father
,当Father
的状态属性变更时,同样会引起组件的刷新,样例运行结果如下图所示:观察静态属性
@ObservedV2 class Manager { @Trace static count: number = 1; } @Entry @ComponentV2 struct Index { build() { Column() { Text(`${Manager.count}`) .onClick(() => { Manager.count++; // 当点击改变count时,Text组件会刷新 }) .width("100%") .backgroundColor("#aabbcc") } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19ObservedV2
装饰类内的静态属性通知支持观察,样例运行结果如下图所示:

请作者喝杯咖啡
©arkui.club版权所有,禁止私自转发、克隆网站。