HarmonyOS 使用ObserverV2的时候,如何传递被@Trace修饰变量的引用?

使用ObserverV2的时候,如何传递被@Trace修饰变量的引用?

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

@ObservedV2现在不允许和@Prop一起使用,会报错。参考demo:

@ObservedV2
class ViewModel {
  @Trace title: string = "开始"
  @Trace title2: string = "t1"
  @Trace observeList: DemoItemObserved[] = []

  loadData() {
    setTimeout(() => {
      this.title = "成功";
      this.title2 = "t2";
      for (let index = 0; index < 4; index++) {
        this.observeList.push(new DemoItemObserved(`张${index}`, "中文学校"))
      }
    }, 2000)
  }
}

@ObservedV2
class DemoItemObserved {
  @Trace title: string = "张大"
  @Trace subTitle: string = "外国语学校"

  constructor(title: string, subTitle: string) {
    this.title = title;
    this.subTitle = subTitle;
  }
}

@Component
struct View1 {
  @Prop title: string
  build() {
    Text(this.title)
  }
}

@Component
struct View2 {
  viewModel: ViewModel = new ViewModel()

  build() {
    List() {
      ForEach(this.viewModel.observeList, (item: DemoItemObserved) => {
        ListItem() {
          Row() {
            Text(item.title)
            Text(item.subTitle)
          }
        }
      })
    }
  }
}

@Entry
@Component
struct Index {
  viewModel: ViewModel = new ViewModel()

  build() {
    Column() {
      Button("模拟加载数据")
        .onClick(() => {
          this.viewModel.loadData()
        })
      Text(this.viewModel.title)
      View1({ title: this.viewModel.title2 })
      View2({ viewModel: this.viewModel })
    }
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
var能否修饰ArkTS中变量
503浏览 • 1回复 待解决
LocalStorageLink修饰变量会自动保存
988浏览 • 1回复 待解决
HarmonyOS Toast弹出时候键盘遮挡
526浏览 • 1回复 待解决
@State 修饰变量值改变,界面不刷新
1562浏览 • 1回复 待解决
自定义弹窗中变量如何传递给页面
2719浏览 • 1回复 待解决