状态管理@ObserveLink,@Observed

霄
2022-11-20 / 0 评论 / 81 阅读 / 正在检测是否收录...

@ObjectLink和@Observed装饰器用于在涉及嵌套对象或数组元素为对象的场景中进行双向数据同步

@Observed
export  class  IndexViewModel{
  message : string;
  price:number;

  constructor(message:string,price:number) {
    this.message=message;
    this.price = price
  }
}
@Component
struct Test {
 @ObjectLink state:IndexViewModel
  build() {
      Row(){
        Text(this.state.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%').justifyContent(FlexAlign.Center)
  }
}


@Entry
@Component
struct Index {
  @State  viewModels:IndexViewModel[]=[
    new IndexViewModel("一号",100),
    new IndexViewModel("二号",120),
    new IndexViewModel("三号",13),
    new IndexViewModel("四号",130),
  ]

  build() {
    Column(){
      ForEach(this.viewModels,(item,index)=>{
        Test({state:item}).onClick(()=>{
          this.viewModels[index].message="123123123";
        })
      })

    }
  }
}
扫描二维码,在手机上阅读!
77

评论

博主关闭了当前页面的评论