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 })
}
}
注意:@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 })
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构