美文网首页ArkTS/ArkUI实战HarmonyOS相关
十三、鸿蒙ArkTS/ArkUI实战-装饰器@Watch

十三、鸿蒙ArkTS/ArkUI实战-装饰器@Watch

作者: ISwiftUI | 来源:发表于2023-11-22 10:11 被阅读0次

    @Watch用于监听状态变量的变化,语法结构为:

    @State @Watch("onChanged") count : number = 0
    

    如上所示,给状态变量增加一个@Watch装饰器,通过@Watch注册一个回调方法onChanged, 当状态变量count被改变时, 触发onChanged回调。

    装饰器@State、@Prop、@Link、@ObjectLink、@Provide、@Consume、@StorageProp以及@StorageLink所装饰的变量均可以通过@Watch监听其变化。

    代码示例:

    // xxx.ets
    @Entry
    @Component
    struct CompA {
        @State @Watch("onChanged") count : number = 0
    
          build() {
            Column() {
              Button('add to basket ' + this.count)
              .margin(15)
              .onClick(() => {
                this.count++
              })
            Text(`${this.count}`)
             .fontSize(30)
          }
        }
    
      // 监听方法
      onChanged: void {}
    }
    

    相关文章

      网友评论

        本文标题:十三、鸿蒙ArkTS/ArkUI实战-装饰器@Watch

        本文链接:https://www.haomeiwen.com/subject/ggcvwdtx.html