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

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

HarmonyOS
2024-12-20 15:45:05
浏览
收藏 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 })
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
分享
微博
QQ
微信
回复
2024-12-20 18:36:34
相关问题
LocalStorageLink修饰变量会自动保存
1755浏览 • 1回复 待解决
var能否修饰ArkTS中变量
1200浏览 • 1回复 待解决
HarmonyOS @builder引用传递问题
1330浏览 • 0回复 待解决
HarmonyOS Toast弹出时候键盘遮挡
1321浏览 • 1回复 待解决
@State 修饰变量值改变,界面不刷新
2607浏览 • 1回复 待解决