HarmonyOS鸿蒙Next V2 状态监听 @Monitor和@Computed

HarmonyOS鸿蒙Next V2 状态监听 @Monitor@Computed

HarmonyOS Next V2 状态监听 @Monitor@Computed

@Monitor 介绍

[@Monitor](/user/Monitor) 是状态把管理V2版本中的用于监听状态变量修改的技术。

它可以直接用在

  1. @ComponentV2装饰的自定义组件中,用于被@Local@Param@Provider@Comsumer[@Computed](/user/Computed)修饰的状态变量中
  2. 对于深层次的数据,如深层次对象、对象数组等,需要搭配@ObservedV2@Trace一起使用。
  3. 可以同时监听多个属性
  4. 可以获取到监听属性的修改前后的数据变化

对比状态管理V1中的@Watch

[@Monitor](/user/Monitor)[@Watch](/user/Watch)功能要强大不少

  1. [@Watch](/user/Watch) 不能用在@ComponentV2修饰的
  2. [@Watch](/user/Watch) 不具备深度监听的功能
  3. [@Watch](/user/Watch) 无法同时监听多个属性
  4. [@Watch](/user/Watch) 无法检测 属性修改前后的变化

@Monitor 监听单个属性

@Entry
@ComponentV2
struct Index {
  @Local num: number = 100

  [@Monitor](/user/Monitor)("num")
  changeNum() {
    console.log("检测到数据的修改啦")
  }

  build() {
    Column () {

      Button(`点击修改 ${this.num}`)
        .onClick(() => {
          this.num++
        })
    }
    .width("100%")
    .height("100%")
  }
}

@Monitor 同时监听多个属性

@Entry
@ComponentV2
struct Index {
  @Local num: number = 100
  @Local age: number = 200

  // 同时监听多个状态的修改
  [@Monitor](/user/Monitor)("num","age")
  changeNum() {
    console.log("检测到数据的修改啦")
  }

  build() {
    Column () {
      Button(`点击修改 num ${this.num}`)
        .onClick(() => {
          this.num++
        })
      Button(`点击修改 age ${this.age}`)
        .onClick(() => {
          this.age++
        })
    }
    .width("100%")
    .height("100%")
  }
}

@Monitor 的回调函数

[@Monitor](/user/Monitor) 的回调函数可以给我们提供这样的能力:

  1. 如果监听了多个状态,而只有一个状态发生变化时, 可以给获知到具体哪个状态发生了变化
  2. 当状态发生变化时,可以获取到变化前后的两个值

[@Monitor](/user/Monitor) 的回调函数的参数是 IMonitor,它是一个对象,拥有两个属性

  1. dirty ,是一个字符串数组,里面存放了修改的状态的名称
  2. value,是一个函数,调用返回会返回一个新的对象,新对象中包含了 path:修改的状态的名称,before:修改前的数据,now:修改后的数据,另外 value() 调用时,如果不传递参数并且你是同时修改多个状态的话,那么它只会返回第一个状态,如果传递了参数-状态变量 那么就会返回该状态变量的相关信息
@Entry
@ComponentV2
struct Index {
  @Local num: number = 100
  @Local age: number = 200

  // 同时监听多个状态的修改
  [@Monitor](/user/Monitor)("num","age")
  changeNum(Monitor: IMonitor) {
    console.log("修改的状态", Monitor.dirty)
    console.log("Monitor.value()", JSON.stringify(Monitor.value("age")))
  }

  build() {
    Column () {
      Button(`同时修改 num 和 age ${this.num}  ${this.age}`)
        .onClick(() => {
          this.num++
          this.age++
        })

    }
    .width("100%")
    .height("100%")
  }
}

@Monitor 深度监听

[@Monitor](/user/Monitor) 需要和 @ObservedV2@Trace一起使用才能实现深度监听的效果,需要注意的是:

  1. [@Monitor](/user/Monitor)可以直接写在 @ObserveV2 修饰的class
  2. [@Monitor](/user/Monitor) 也可以写在正常的组件内
@ObservedV2
class Person {
  @Trace son: Son = new Son()
}

@ObservedV2
class Son {
  // [@Monitor](/user/Monitor)可以直接写在 @ObserveV2 修饰的class中
  [@Monitor](/user/Monitor)("weight")
  weightChange() {
    console.log("1 儿子的体重修改了")
  }

  @Trace weight: number = 200
}

@Entry
@ComponentV2
struct Index {
  person: Person = new Person()
    // [@Monitor](/user/Monitor) 也可以写在正常的组件内
  [@Monitor](/user/Monitor)("person.son.weight")
  weightChange() {
    console.log("2 儿子的体重呗修改了")
  }

  build() {
    Column () {
      Button(`修改儿子的体重${this.person.son.weight}`)
        .onClick(() => {
          this.person.son.weight++
        })
    }
    .width("100%")
    .height("100%")
  }
}

@Monitor的限制

在实际开发使用中,[@Monitor](/user/Monitor)也存在一些限制,无法监听内置类型(ArrayMapDateSet)的API调用引起的变化,如当你检测整个数组时,你对数组使用 pushsplice等常见方法修改数组,是无法检测到的。当然,当整个数组被重新赋值时,可以检测到它的变化

@ObservedV2
class Person {
  @Trace name: string = "小明"
}

@Entry
@ComponentV2
struct Index {
  @Local
  personList: Person[] = [new Person()]

  [@Monitor](/user/Monitor)("personList")
  weightChange() {
    console.log(" 检测到数组修改了")
  }

  build() {
    Column () {
      Button("增加一个")
        .onClick(() => {
          // 1 无效 - 无法检测到数组发生了修改
          this.personList.push(new Person())

          // 2 有效 检测到了数组发生修改
          // const newPerson = [...this.personList, new Person()]
          // this.personList = newPerson
        })
      ForEach(this.personList, (item: Person) => {
        Text(item.name)
      })
    }
    .width("100%")
    .height("100%")
  }
}

另外可以通过.语法或者监听数组长度来变向实现检测数组元素发生变化

.语法

@ObservedV2
class Person {
  @Trace name: string = "小明"
}

@Entry
@ComponentV2
struct Index {
  @Local
  personList: Person[] = [new Person()]

  [@Monitor](/user/Monitor)("personList.0")
  // 如果要单独监听对象中的某个属性  [@Monitor](/user/Monitor)("personList.0.name")
  weightChange() {
    console.log(" 检测到数组修改了")
  }

  build() {
    Column () {
      Button("增加一个")
        .onClick(() => {
          const p = new Person()
          p.name = "小黑"
          this.personList[0] = p
        })
      ForEach(this.personList, (item: Person) => {
        Text(item.name)
      })
    }
    .width("100%")
    .height("100%")
  }
}

监听数组长度变化

@ObservedV2
class Person {
  @Trace name: string = "小明"
}

@Entry
@ComponentV2
struct Index {
  @Local
  personList: Person[] = [new Person()]

  [@Monitor](/user/Monitor)("personList.length")
  weightChange() {
    console.log(" 检测到数组修改了")
  }

  build() {
    Column () {
      Button("增加一个")
        .onClick(() => {
          const p = new Person()
          p.name = "小黑"
          this.personList.push(p)
        })
      ForEach(this.personList, (item: Person) => {
        Text(item.name)
      })
    }
    .width("100%")
    .height("100%")
  }
}

@Computed

[@Computed](/user/Computed)为计算属性,可以监听数据变化,从而计算新的值。用法比较简单

@Entry
@ComponentV2
struct Index {
  @Local num: number = 100

  [@Computed](/user/Computed)
  get numText() {
    return this.num * 2
  }

  build() {
    Column () {
      Button("修改")
        .onClick(() => {
          this.num++
        })
      Text(`原数据 ${this.num}`)
      Text(`计算后 ${this.numText}`)
    }
    .width("100%")
    .height("100%")
  }
}

更多关于HarmonyOS鸿蒙Next V2 状态监听 @Monitor和@Computed的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next V2中,@Monitor@Computed是用于状态监听和计算属性的装饰器。@Monitor用于监听状态的变化,当被监听的状态发生变化时,会触发相应的回调函数。@Computed用于定义计算属性,它会根据依赖的状态自动更新其值,适用于那些依赖于其他状态且需要进行复杂计算的场景。这两个装饰器可以帮助开发者更高效地管理应用的状态和逻辑。

更多关于HarmonyOS鸿蒙Next V2 状态监听 @Monitor和@Computed的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next V2中,[@Monitor](/user/Monitor)[@Computed](/user/Computed) 是用于状态监听和计算的装饰器。

  • @Monitor: 用于监听状态的变化。当被监听的状态发生变化时,绑定的方法会自动执行。适用于需要在状态变化时执行特定逻辑的场景。

  • @Computed: 用于派生状态,基于其他状态计算得出新值。当依赖的状态变化时,[@Computed](/user/Computed) 属性会自动重新计算,确保数据始终是最新的。

这两个装饰器帮助开发者更高效地管理状态依赖和更新逻辑,提升应用性能。

回到顶部