ObservedV2装饰器和Trace装饰器

为了对嵌套类对象属性变化直接观测,华为提供了ObservedV2和Trace装饰器。这两个装饰器必须搭配使用,单独使用任何一个都不会起任何作用;在继承类中也可监测;ObservedV2的类实例目前不支持使用JSON.stringify进行序列化,需通过new操作符实例化后,才具备被观测变化的能力。与V1版本相比(使用@ObjectLink装饰器与自定义组件来实现观测),使用起来更加方便。

嵌套类场景

在下面场景中老师(Teacher)尹山木,有个学生(Student)丁云飞,高一有三门课程(语文,数学,英语),升到高二增加了一门化学课。

export class Teacher{
  name:string = "尹山木"
  student:Student
  constructor(stu:Student) {
    this.student = stu
  }
}
export class Student{
  name:string = "丁云飞"
  course:Course
  constructor(c:Course) {
    this.course = c
  }
}
@ObservedV2
export class Course{
  @Trace courses:Array<string> = []
  constructor() {
    this.courses = ["语文","数学","英语"]
  }
}
@Entry
@ComponentV2
struct Index {
@Local teacher:Teacher = new Teacher(new Student(new Course()))
  build() {
     Column({space:20}){
       Text("老师:" + this.teacher.name)
         .fontSize(20)
       Text("学生:" + this.teacher.student.name)
         .fontSize(18)
         Row({space:6}){
           ForEach(this.teacher.student.course.courses,(course:string,index)=>{
             Text("课程:" + course)
             .fontSize(16)
         })
         }.width('100%')
         .justifyContent(FlexAlign.Start).alignItems(VerticalAlign.Center)
        Button("升上二年级")
          .onClick(()=>{
            this.teacher.student.course.courses.push("化学")
          })
     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

运行效果点击升上二年级,可以看到课程增加了一门化学。

继承类场景

祖孙三人,每过一年,年龄增加一岁。


@ObservedV2
export class GrandFather{
  @Trace age:number = 0
  constructor(age:number) {
    this.age = age;
  }
}
export class Father extends GrandFather{
  constructor(age:number) {
    super(age)
  }
}
export class Son extends Father{
  constructor(age: number) {
    super(age)
  }
}
@Entry
@ComponentV2
struct Index {
@Local son:Son = new Son(2)
  build() {
     Column({space:20}){
       Text("孩子今年:" + this.son.age + "岁了!")
         .fontSize(20)

        Button("过了一年")
          .onClick(()=>{
            this.son.age++
          })
     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

点击过了一年孩子会增长一岁。

Trace装饰基础类型的数组

ObservedV2监听模型numArrModel的numberArr数组的增加,同时刷新UI
@ObservedV2
export class numArrModel{
  id:number = 0
  @Trace numberArr:Array<number> = [0,10,5]
}
@Entry
@ComponentV2
struct Index {
@Local numModel:numArrModel = new numArrModel()
  build() {
     Column({space:20}){
       ForEach(this.numModel.numberArr,(item:number,index)=>{
         Text(''+item)
           .fontSize(20)
       })
       Button('增加一个数字')
         .onClick(()=>{
            this.numModel.numberArr.push(11)
         })
       Button('减少一个数字')
         .onClick(()=>{
           this.numModel.numberArr.pop()
         })
     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

Trace装饰对象数组

Trace装饰对象数组studends,以及student的属性age。当数组长度和age改变时页面会刷新。

@ObservedV2
export class Student{
  @Trace age:number = 1
}
@ObservedV2
export class Classes{
  id:number = 3
  @Trace studends:Student[] = []
  constructor(stus:Student[]) {
    this.studends = stus
  }
}
@Entry
@ComponentV2
struct Index {
@Local classModel:Classes = new Classes([new Student(),new Student(),new Student()])
  build() {
     Column({space:20}){
      Column(){
        Text("班级:"+this.classModel.id)
          .fontSize(20)
        Text("学生数量:"+this.classModel.studends.length+"人")
          .fontSize(20)
      }
      Column(){
        ForEach(this.classModel.studends,(stu:Student,index)=>{
          Text("年龄:"+stu.age)
            .fontSize(20)
        })
      }
       Button('增加一个学生')
         .onClick(()=>{
            this.classModel.studends.push(new Student())
         })
       Button('第一名学生年龄增加一岁')
         .onClick(()=>{
           if (this.classModel.studends.length > 0) {
             this.classModel.studends[0].age++
           }
         })
     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

Trace装饰Map类型

Trace装饰的Map类型属性,当发生set、clear、delete事件时会被监测到。

@ObservedV2
export class textMapModel{
  @Trace textMap:Map<number,string> = new Map([[0,'a'],[1,'b'],[2,'c']])
}
@Entry
@ComponentV2
struct Index {
@Local mapInfo:textMapModel = new textMapModel()
  build() {
     Column({space:20}){
       ForEach(Array.from(this.mapInfo.textMap.entries()), (item: [number, string]) => {
         Text(`${item[0]}`)
           .fontSize(30)
         Text(`${item[1]}`)
           .fontSize(30)
         Divider()
       })
       Button('初始化').onClick(()=>{
        this.mapInfo.textMap = new Map([[0,'z'],[1,'x'],[2,'c']])
       })
       Button('增加一个').onClick(()=>{
        this.mapInfo.textMap.set(3,'v')
       })
       Button('删除一个').onClick(()=>{
         this.mapInfo.textMap.delete(0)

       })
       Button('清除').onClick(()=>{
         this.mapInfo.textMap.clear()
       })
       Button('改变值').onClick(()=>{
         this.mapInfo.textMap.set(0,'city')
       })

     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

Trace装饰Set类型

Trace装饰的Set类型属性可以观测到add, clear, delete等

@ObservedV2
export class Info{
  @Trace memberSet:Set<number> = new Set([0,1,2,3,4,5,6,])
}
@Entry
@ComponentV2
struct Index {
@Local memberInfoModel:Info = new Info()
  build() {
     Column({space:20}){
      Row(){
        ForEach(Array.from(this.memberInfoModel.memberSet.values()),(item:number)=>{
          Text(``+item)
            .fontSize(20)
            .margin({left:6})

        })
      }
       Button('add').onClick(()=>{
         this.memberInfoModel.memberSet.add(10)
       })
       Button('clear').onClick(()=>{
         this.memberInfoModel.memberSet.clear()
       })
       Button('delete').onClick(()=>{
         this.memberInfoModel.memberSet.delete(0)

       })
     }.justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .padding({left:20})
  }
}

Trace装饰Date类型

@Trace装饰的Date类型属性可以观测调用API带来的变化,包括 setFullYear、setMonth、setDate、setHours、setMinutes、setSeconds、setMilliseconds、setTime、setUTCFullYear、setUTCMonth、setUTCDate、setUTCHours、setUTCMinutes、setUTCSeconds、setUTCMilliseconds。因为Info类被@ObservedV2装饰且属性selectedDate被@Trace装饰,点击Button('set selectedDate to 2023-07-08')对selectedDate赋值也可以观测到变化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值