Harmony 状态监听 @Monitor和@Computed

简介: Harmony 状态监听 @Monitor和@Computed

Harmony 状态监听 @Monitor和@Computed

@Monitor 介绍

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

它可以直接用在

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

对比状态管理V1中的@Watch

@Monitor@Watch功能要强大不少

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

@Monitor 监听单个属性

@Entry
@ComponentV2
struct Index {
  @Local num: number = 100
  @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("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 的回调函数可以给我们提供这样的能力:

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

@Monitor 的回调函数的参数是 IMonitor,它是一个对象,拥有两个属性

  1. dirty ,是一个字符串数组,里面存放了修改的状态的名称
  2. value,是一个函数,调用返回会返回一个新的对象,新对象中包含了 path:修改的状态的名称,before:修改前的数据,now:修改后的数据,另外 value() 调用时,如果不传递参数并且你是同时修改多个状态的话,那么它只会返回第一个状态,如果传递了参数-状态变量 那么就会返回该状态变量的相关信息
@Entry
@ComponentV2
struct Index {
  @Local num: number = 100
  @Local age: number = 200
  // 同时监听多个状态的修改
  @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 需要和 @ObservedV2@Trace一起使用才能实现深度监听的效果,需要注意的是:

  1. @Monitor可以直接写在 @ObserveV2 修饰的class
  2. @Monitor 也可以写在正常的组件内
@ObservedV2
class Person {
  @Trace son: Son = new Son()
}
@ObservedV2
class Son {
  // @Monitor可以直接写在 @ObserveV2 修饰的class中
  @Monitor("weight")
  weightChange() {
    console.log("1 儿子的体重修改了")
  }
  @Trace weight: number = 200
}
@Entry
@ComponentV2
struct Index {
  person: Person = new Person()
    // @Monitor 也可以写在正常的组件内
  @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也存在一些限制,无法监听内置类型(ArrayMapDateSet)的API调用引起的变化,如当你检测整个数组时,你对数组使用 pushsplice等常见方法修改数组,是无法检测到的。当然,当整个数组被重新赋值时,可以检测到它的变化

@ObservedV2
class Person {
  @Trace name: string = "小明"
}
@Entry
@ComponentV2
struct Index {
  @Local
  personList: Person[] = [new Person()]
  @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%")
  }
}
另外可以通过.语法或者监听数组长度来变向实现检测数组元素发生变化
.语法
typescript
代码解读
复制代码
@ObservedV2
class Person {
  @Trace name: string = "小明"
}
@Entry
@ComponentV2
struct Index {
  @Local
  personList: Person[] = [new Person()]
  @Monitor("personList.0")
  // 如果要单独监听对象中的某个属性  @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("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为计算属性,可以监听数据变化,从而计算新的值。用法比较简单

@Entry
@ComponentV2
struct Index {
  @Local num: number = 100
  @Computed
  get numText() {
    return this.num * 2
  }
  build() {
    Column() {
      Button("修改")
        .onClick(() => {
          this.num++
        })
      Text(`原数据 ${this.num}`)
      Text(`计算后 ${this.numText}`)
    }
    .width("100%")
    .height("100%")
  }
}

目录
相关文章
|
12月前
|
监控 JavaScript 前端开发
05avalon - vm监控属性 ($watch)
05avalon - vm监控属性 ($watch)
65 0
computed【计算属性】watch【监听】methods【方法】的区别
computed【计算属性】watch【监听】methods【方法】的区别
|
25天前
|
前端开发
this.props.history.listen路由监听与取消监听
在React中使用`this.props.history.listen`进行路由变化监听,并在组件卸载时通过调用返回的函数取消监听,以避免不必要的回调执行或内存泄漏。
28 2
|
2月前
|
前端开发 JavaScript 算法
React Server Component 使用问题之想在路由切换时保持客户端状态,如何实现
React Server Component 使用问题之想在路由切换时保持客户端状态,如何实现
|
3月前
|
API
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
838 1
|
3月前
|
JavaScript API
vue3【实用教程】侦听器 watch,自动侦听 watchEffect(),$watch,手动停止侦听器
vue3【实用教程】侦听器 watch,自动侦听 watchEffect(),$watch,手动停止侦听器
73 0
|
5月前
|
缓存 JavaScript
computed/watch深度监听
computed/watch深度监听
158 1
|
5月前
|
设计模式 缓存
proxy与watch的关系【了解】
proxy与watch的关系【了解】
18 0
|
JavaScript
state 和 props 触发更新的生命周期分别有什么区别?
state 和 props 触发更新的生命周期分别有什么区别?
|
5月前
如何监听vuex中的变量参数变化,用watch!
如何监听vuex中的变量参数变化,用watch!