HarmonyOS-基础之@Watch监听、@ObjectLink和@Observed

1、Watch监听

类似Vue中的数据监听,监听的数据发生了变化 --> 做啥事情

父组件

import Child07 from '../components/Child07'

@Entry
@Component
struct WatchExample {
  // watch 可以监听组件状态 State | Link | Provide ......
  @State @Watch('update') obj: {
    a: number,
    b: { c: number }
  } = { a: 123, b: { c: 456 } }

  // watch的监听回调
  update() {
    console.log('监听到obj的变化')
  }

  build() {
    Column() {
      Text('watch监听').fontSize(20)
      // 子组件
      // Child07({ obj: this.obj })
      Child07({obj:$obj})
    }.width("100%")
  }
}

子组件

@Component
export default struct Child07 {
  // Prop好像监测不到
  // @Prop obj: {
  //   a: number,
  //   b: { c: number }
  // }

  @Link obj: {
    a: number,
    b: { c: number }
  }

  build() {
    Column() {
      Text('子组件Child07获取父组件传递的数据obj:' + JSON.stringify(this.obj))
      Button('修改父组件@Watch监听的数据').onClick((event: ClickEvent) => {
        // this.obj = { a: 20, b: { c: 30 } }
        this.obj.a += 100
        // 无法深度监听
        // this.obj.b.c += 9
      })
    }
    .width('100%')
    .border({ width: 1, color: Color.White })
  }
}

image

注意:@Watch是浅监听,上面的案例也可以看出;至于深度监听的写法后面会演示

2、ObjectLink和Observed

从前面的Watch可以看出对象中的对象或者数组中的对象属性等深层次的属性变化时UI无法更新;所以ObjectLink和Observed就可以来解决这个问题了;
案例如下:

Person对象

@Observed
export class Person {
  id: number
  name: string
  age: number

  constructor(id: number, name: string, age: number) {
    this.id = id
    this.name = name
    this.age = age
  }
}

父组件

import { Person } from '../domain/Model'
import Item01 from '../components/Item01'

@Entry
@Component
struct ObjectLinkExample {
  @State userArr: Person[] = [new Person(1, 'zs', 19), new Person(2, 'ls', 23)]

  build() {
    Column() {
      Text(JSON.stringify(this.userArr)).onClick(() => {
        console.log(JSON.stringify(this.userArr))
      })
      Button('更新数据').onClick((event: ClickEvent) => {
        this.userArr[0].age += 1
      })
      ForEach(this.userArr, (item: Person, index: number) => {
        Item01({ item: item })
      })
    }.width('100%')
  }
}

子组件

import { Person } from '../domain/Model'

@Component
export default struct Item01 {
  @ObjectLink item: Person

  build() {
    Column() {
      Text('Item01子组件,通过@Observed和@ObjectLink获取到父组件传递的数据:' + JSON.stringify(this.item))
      Button('更新数据').onClick((event: ClickEvent) => {
        this.item.age += 1
      })
    }.width('100%')
    .padding(20)
    .border({ width: 1, color: Color.Red })
  }
}

image

image

posted @   我也有梦想呀  阅读(414)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示