HarmonyOS API12中ObservedV2结合Trace怎么更新子view。

API12中ObservedV2结合Trace怎么更新子view。

HarmonyOS
2024-12-20 15:52:34
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

现在@prop与@observed联用会出现错误,可以修改关键代码如下:

@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.
  • 72.
  • 73.
分享
微博
QQ
微信
回复
2024-12-20 18:03:04
相关问题
HarmonyOS @ObservedV2不支持{} as Father对象
825浏览 • 1回复 待解决
HarmonyOS API12是否有json解析工具
988浏览 • 1回复 待解决
Api12 arm模拟器无法启动
1162浏览 • 1回复 待解决
HarmonyOS 针对API12:组件使用场景dialog
1109浏览 • 1回复 待解决
HarmonyOS API12之后是否不允许uv_poll
936浏览 • 1回复 待解决
HarmonyOS libEGL.so库在 API12 上不见了
1426浏览 • 1回复 待解决