3 回复
我们开发的时候,经常会碰到比如业务状态比较多,状态变化难管理,或者父子组件状态同步变更等各种问题,所以我们今天来通过@Watch来实现跨组件的状态联动来解决这些难题。
核心实现步骤
一、我们在父组件中定义 @State 响应式变量;
二、在子组件中通过 @Link 接收父状态,建立一个双向绑定;
三、在子组件中用 @Watch(‘变量名’) 来装饰一个方法;
四、在监听方法中编写其他逻辑;
五、父组件更新状态时,子组件自动触发监听回调。
实现思路:
使用 [@Watch](/user/Watch) 装饰器来监听 [@State](/user/State) 或 [@Link](/user/Link) 变量值的变化,当被监听变量值更新时,自动去触发回调函数来进行属性变更 。
例如:
// 在子组件中监听父组件传入的link变量
[@Link](/user/Link) linkCount: number;
[@Watch](/user/Watch)('linkCount')
onCountChange(newVal: number, oldVal: number) {
console.info(`计数从 ${oldVal} 变为 ${newVal}`);
// 可在此执行动画、日志、副作用等
}
实现完整代码 如下:
@Component
export struct CounterDisplay {
[@Link](/user/Link) linkCount: number;
// 监听linkCount变化
[@Watch](/user/Watch)('linkCount')
onCountChange(newVal: number, oldVal: number) {
if (newVal > 10) {
console.warn('计数超过10!');
}
}
build() {
Text(`当前值:${this.linkCount}`)
.fontSize(20)
.padding(10)
.backgroundColor('#E6F7FF')
.borderRadius(8)
}
}
@Component
@Entry
struct WatchDemo {
[@State](/user/State) count: number = 0;
build() {
Column({ space: 20 }) {
Text('[@Watch](/user/Watch) 跨组件联动示例')
.fontSize(18)
.fontWeight(FontWeight.Bold)
// 子组件通过[@Link](/user/Link)绑定父状态
CounterDisplay({ linkCount: $count })
Row({ space: 15 }) {
Button('+1')
.onClick(() => {
this.count++;
})
Button('-1')
.onClick(() => {
this.count--;
})
Button('重置')
.onClick(() => {
this.count = 0;
})
}
}
.padding(30)
.width('100%')
.height('100%')
}
}
更多关于HarmonyOS鸿蒙Next中通过@Watch实现跨组件状态联动的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,@Watch装饰器是实现跨组件状态联动的关键工具。它用于监听状态变量的变化,当被监听的变量发生改变时,会自动触发关联的回调函数,从而实现组件间的状态同步。
基本用法
- 定义状态变量:使用
@State或@Link装饰器定义需要被监听的状态。 - 添加
@Watch监听:在需要响应状态变化的组件中,使用@Watch装饰器指定回调函数。 - 回调函数执行:当状态变化时,回调函数自动执行,可在此更新其他状态或执行逻辑。
示例代码
@Entry
@Component
struct ParentComponent {
@State count: number = 0;
build() {
Column() {
Button('增加计数')
.onClick(() => {
this.count += 1;
})
ChildComponent({ count: $count })
}
}
}
@Component
struct ChildComponent {
@Link @Watch('onCountChange') count: number;
onCountChange() {
console.log(`计数已更新为: ${this.count}`);
// 可在此触发其他组件的状态更新
}
build() {
Text(`当前计数: ${this.count}`)
}
}
注意事项
@Watch回调函数在状态变化后同步执行。- 避免在回调中进行耗时操作,以免阻塞UI更新。
- 多个
@Watch监听同一变量时,执行顺序与声明顺序一致。
通过合理使用@Watch,可以高效实现组件间的解耦和状态联动,提升应用的可维护性。

