HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新

发布于 1周前 作者 sinazl 来自 鸿蒙OS

HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新 viewModel里数据刷新如何触发struct里组件刷新

3 回复

基础类型不支持传递,要用引用类型,比如object,而且传递后不能再new,否则导致引用丢失无法刷新

更多关于HarmonyOS鸿蒙Next中viewModel里数据刷新如何触发struct里组件刷新的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,ViewModel的数据刷新可以通过[@Observed](/user/Observed)@ObjectLink装饰器来触发struct里组件的刷新。具体步骤如下:

  1. 定义ViewModel:在ViewModel中定义需要观察的数据,并使用[@Observed](/user/Observed)装饰器标记该类,以便系统能够监听其变化。

    [@Observed](/user/Observed)
    class MyViewModel {
        public data: string = "Initial Data";
    }
  2. 绑定ViewModel:在struct中通过@ObjectLink装饰器将ViewModel的实例绑定到组件中。这样,当ViewModel中的数据发生变化时,绑定的组件会自动刷新。

    [@Component](/user/Component)
    struct MyComponent {
        @ObjectLink viewModel: MyViewModel;
    
        build() {
            Column() {
                Text(this.viewModel.data)
                    .fontSize(20)
            }
        }
    }
  3. 更新数据:在ViewModel中更新数据时,系统会自动检测到变化并触发struct中相关组件的刷新。

    let viewModel = new MyViewModel();
    viewModel.data = "Updated Data"; // 这将触发MyComponent中的Text组件刷新

通过这种方式,ViewModel中的数据变化可以自动触发struct中组件的刷新,无需手动调用刷新方法。

在HarmonyOS鸿蒙Next中,ViewModel通过@Observed@State等装饰器实现数据绑定。当ViewModel中的数据变化时,会自动触发依赖该数据的struct组件刷新。具体步骤:

  1. 在ViewModel中定义@Observed@State变量。
  2. struct中使用@Observed@State变量绑定UI组件。
  3. 当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组件自动刷新。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!