HarmonyOS应用如何实现实时数据更新?

HarmonyOS应用如何实现实时数据更新?

阅读 749
1 个回答

如果是在封装了很多自定义组件的情况下,可以结合使用@ObjectLink 和@Observed。例如:

@Observed 
class MyViewModel { 
  title: string = "" 
  constructor(title:string) { 
    this.title = title 
  } 
} 

@Entry 
@Component 
export struct MyComponent { 

  @State vm: MyViewModel = new MyViewModel("1") 

  build() { 
    Row(){ 
      OtherComponenft({vm:this.vm}) 
       .onClick(()=>{ 
          this.vm.title = "222" 
        }) 
    }.width("100%") 
   .height(100) 
  } 
} 

@Component 
struct OtherComponenft { 
  @ObjectLink vm: MyViewModel 
  build() { 
    Text(this.vm.title) 
     .fontSize(20) 
     .fontColor(Color.Black) 
     .width(200) 
     .height(50) 
     .margin({ 
        left:20 
      }) 
  } 
}
推荐问题