鸿蒙5:V2常用装饰器
·
目录
1.常用装饰器
1.1 @Local巩固
参考地址
@Local表示组件内部的状态,使得自定义组件内部的变量具有观测变化的能力:
- 被@Local装饰的变量无法从外部初始化,因此必须在组件内部进行初始化。
- 当被@Local装饰的变量变化时,会刷新使用该变量的组件。
- @Local支持观测number、boolean、string、Object、class等基本类型以及Array、Set、Map、Date等内嵌类型。
- @Local的观测能力仅限于被装饰的变量本身。当装饰简单类型时,能够观测到对变量的赋值;当装饰对象类型时,仅能观测到对对象整体的赋值;当装饰数组类型时,能观测到数组整体以及数组元素项的变化;当装饰Array、Set、Map、Date等内嵌类型时,可以观测到通过API调用带来的变化。详见观察变化。
- @Local支持null、undefined以及联合类型。
1.2 @ObservedV2 和 @Trace装饰器
1.2.1 基本介绍
为了增强状态管理框架对类对象中属性的观测能力,开发者可以使用@ObservedV2装饰器和@Trace装饰器装饰类以及类中的属性。
@ObservedV2装饰器与@Trace装饰器用于装饰类以及类中的属性,使得被装饰的类和属性具有深度观测的能力:
- @ObservedV2装饰器与@Trace装饰器需要配合使用,单独使用@ObservedV2装饰器或@Trace装饰器没有任何作用。
- 被@Trace装饰器装饰的属性property变化时,仅会通知property关联的组件进行刷新。
- 在嵌套类中,嵌套类中的属性property被@Trace装饰且嵌套类被@ObservedV2装饰时,才具有触发UI刷新的能力。
- 在继承类中,父类或子类中的属性property被@Trace装饰且该property所在类被@ObservedV2装饰时,才具有触发UI刷新的能力。
- 未被@Trace装饰的属性用在UI中无法感知到变化,也无法触发UI刷新。
1.2.2 错误示例
@Entry
@ComponentV2
struct ObservedV2Demo {
@Local user: People = new People('张三', 21)
build() {
Column() {
Text('姓名:' + this.user.name)
Text('年龄:' + this.user.age)
Button('修改')
.onClick(() => {
this.user.name = '李四'
this.user.age = 30
})
}
.height('100%')
.width('100%')
}
}
class People {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
1.2.3 正确示例
@Entry
@ComponentV2
struct ObservedV2Demo {
@Local user: People = new People('张三', 21)
build() {
Column() {
Text('姓名:' + this.user.name)
Text('年龄:' + this.user.age)
Button('修改')
.onClick(() => {
this.user.name = '李四'
this.user.age = 30
})
}
.height('100%')
.width('100%')
}
}
@ObservedV2
class People {
@Trace name: string
@Trace age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
1.2.4 数组嵌套对象
@Entry
@ComponentV2
struct ObservedV2Demo2 {
@Local students: Student[] = [new Student('张三', 20), new Student('李四', 30)]
build() {
Column() {
ForEach(this.students, (item: Student) => {
Column() {
Text('姓名:' + item.name)
Text('年龄:' + item.age)
Button('修改')
.onClick(() => {
item.age++
})
}
})
}
.height('100%')
.width('100%')
}
}
@ObservedV2
class Student {
name: string
@Trace age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
更多推荐


所有评论(0)