HarmonyOS @Watch装饰器,能监听对象中某个属性的变化值吗?

HarmonyOS
2024-12-18 16:42:41
819浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang
@Entry
@Component
struct testPage {
  @State @Watch('change') person: Person = new Person('Peppa', 25, 'male')
  @State message: string = 'Hello World';
  @State nameTemp: string = this.person.name
  @State ageTemp: number = this.person.age
  @State genderTemp: string = this.person.gender

  //
  change() {
    // console.log(`信息改变了:${JSON.stringify(this.person)}`)
    if (this.nameTemp !== this.person.name) {
      console.log(`名字信息改变了:${JSON.stringify(this.person.name)}`)
      //处理名字属性改变的逻辑/调用相关方法
    }
    if (this.ageTemp !== this.person.age) {
      console.log(`年龄信息改变了:${JSON.stringify(this.person.age)}`)
      //处理年龄属性改变的逻辑/调用相关方法
    }
    if (this.genderTemp !== this.person.gender) {
      console.log(`性别信息改变了:${JSON.stringify(this.person.gender)}`)
      //处理性别属性改变的逻辑/调用相关方法
    }

  }

  build() {
    Column({ space: 10 }) {
      Text(`当前信息:${JSON.stringify(this.person)}`)
      Button() {
        Text('11点击一下')
      }.type(ButtonType.Capsule).padding({ left: 5, right: 5 }).onClick(() => {
        let person = new Person('Utopia', 25, 'female')
        this.person = person
      })

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}


class Person {
  constructor(name: string, age: number, gender: string) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }

  name: string
  age: number
  gender: string
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
分享
微博
QQ
微信
回复
2024-12-18 19:33:26


相关问题
HarmonyOS 装饰数据变化监听
581浏览 • 1回复 待解决
如何监听数组内对象属性变化
3143浏览 • 1回复 待解决
HarmonyOS 使用@Watch观察变化问题
606浏览 • 1回复 待解决
@Watch装饰回调执行顺序
943浏览 • 1回复 待解决
HarmonyOS 如何监听某个变量是否变化
731浏览 • 1回复 待解决