如何监听数组内对象属性变化?

如何监听数组内对象属性变化

阅读 942
1 个回答

通过@Observed配合@ObjectLink装饰符实现。@Observed用于类,@ObjectLink用于变量。

  1. 在类上使用@Observed。
let NextID: number = 1;   
 
@Observed   
class ClassA {   
  public id: number;   
  public c: number = 0;   
 
  constructor(c: number) {   
    this.id = NextID++;   
    this.c = c;   
  }   
}
  1. 在组件变量使用@ObjectLink。
@Component   
struct ViewA {   
  @ObjectLink item: ClassA;   
 
  build() {   
    Column() {   
      Text(`ViewA: id = ${this.item.id}, c = ${this.item.c}`)   
        .margin({ top: 20 })   
      Button(`ViewA: this.item.c++`)   
        .onClick(() => {   
          this.item.c++;   
        })   
        .margin({ top: 20 })   
    }    .backgroundColor('#F1F3F5')   
    .borderRadius('12vp')   
    .margin({ top: 20 })   
  }   
}
  1. 创建对象数组。此时@State无法订阅到数组成员的属性变化,点击按钮“Index: this.itemArr[0].c = x”不会更新。自定义组件ViewA中@ObjectLink可以订阅到属性变化,可以触发组件内容刷新。
@Entry   
@Component   
struct Index {   
  @State itemArr: ClassA[] = [new ClassA(0), new ClassA(1)];   
 
  build() {   
    Column() {   
      ForEach(this.itemArr,   
        (item: ClassA) => {   
          Text(`Index: this.itemArr[0].c = ${this.itemArr[0].c}`)   
            .margin({ top: 20 })   
          ViewA({ item: item })   
        }, (item: ClassA, index: number) => index + JSON.stringify(item))   
 
      Button(`Index: this.itemArr[0].c++`)   
        .onClick(() => {   
          this.itemArr[0].c++;   
        })   
        .margin({ top: 20 })   
 
      Button(`Index: reset array`)   
        .onClick(() => {   
          this.itemArr = [new ClassA(0), new ClassA(0)];   
        })   
        .margin({ top: 20 })   
      Button(`Index: push`)   
        .onClick(() => {   
          this.itemArr.push(new ClassA(0))   
        })   
        .margin({ top: 20 })   
    }    .width('100%')   
  }   
}

参考链接

Observed和ObjectLink数据管理

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进