HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新
HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新 viewModel里数据刷新如何触发struct里组件刷新
基础类型不支持传递,要用引用类型,比如object,而且传递后不能再new,否则导致引用丢失无法刷新
更多关于HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,ViewModel的数据刷新可以通过[@Observed](/user/Observed)和@ObjectLink装饰器来触发struct里组件的刷新。具体步骤如下:
-
定义ViewModel:在
ViewModel中定义需要观察的数据,并使用[@Observed](/user/Observed)装饰器标记该类,以便系统能够监听其变化。[@Observed](/user/Observed) class MyViewModel { public data: string = "Initial Data"; } -
绑定ViewModel:在
struct中通过@ObjectLink装饰器将ViewModel的实例绑定到组件中。这样,当ViewModel中的数据发生变化时,绑定的组件会自动刷新。[@Component](/user/Component) struct MyComponent { @ObjectLink viewModel: MyViewModel; build() { Column() { Text(this.viewModel.data) .fontSize(20) } } } -
更新数据:在
ViewModel中更新数据时,系统会自动检测到变化并触发struct中相关组件的刷新。let viewModel = new MyViewModel(); viewModel.data = "Updated Data"; // 这将触发MyComponent中的Text组件刷新
通过这种方式,ViewModel中的数据变化可以自动触发struct中组件的刷新,无需手动调用刷新方法。
在HarmonyOS鸿蒙Next中,ViewModel通过@Observed和@State等装饰器实现数据绑定。当ViewModel中的数据变化时,会自动触发依赖该数据的struct组件刷新。具体步骤:
- 在ViewModel中定义
@Observed或@State变量。 - 在
struct中使用@Observed或@State变量绑定UI组件。 - 当ViewModel中数据变化时,依赖该数据的UI组件会自动刷新。
例如:
@Observed class MyViewModel {
@State count = 0;
}
@Entry
@Component
struct MyComponent {
private viewModel: MyViewModel = new MyViewModel();
build() {
Column() {
Text(`Count: ${this.viewModel.count}`)
Button('Increment').onClick(() => {
this.viewModel.count++;
})
}
}
}
点击按钮时,count变化,Text组件自动刷新。

