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 })
    }
  }
}
分享
微博
QQ
微信
回复
2024-12-20 18:03:04
相关问题
HarmonyOS @ObservedV2不支持{} as Father对象
360浏览 • 1回复 待解决
HarmonyOS API12是否有json解析工具
452浏览 • 1回复 待解决
HarmonyOS 针对API12:组件使用场景dialog
556浏览 • 1回复 待解决
Api12 arm模拟器无法启动
709浏览 • 1回复 待解决
HarmonyOS API12之后是否不允许uv_poll
466浏览 • 1回复 待解决