DEV Community

HarmonyOS
HarmonyOS

Posted on

Why do we need viewmodel in ArkTs?

Read the original article:Why do we need viewmodel in ArkTs?

Requirement Description

In ArkTS, UI components are built using Page and Component structures. However, as applications become more complex, managing UI state, business logic, and data transformations within these structures becomes difficult.

Background Knowledge

ViewModel is introduced to separate concerns, centralize state management, and ensure reusability. ArkTS uses a declarative and reactive UI model, where the view is automatically updated when the underlying state changes.
In small applications, using @State, @Link, or @Prop inside a Page or Component is sufficient. However, problems arise when:

  • State and logic are duplicated across components
  • UI becomes bloated with business logic
  • Testing UI-bound logic becomes difficult
  • Multiple pages need to share the same state or logic

Implementation Steps

  1. Define the ViewModel
  2. Reference ViewModel in Page or Component
  3. Bind UI with ViewModel state
  4. Preserve and use the ViewModel

Code Snippet / Configuration

export class YourViewModel {
  async yourList(): Promise<string[]> {
    return [
      "Hey",
      "I am",
      "Your",
      "Example",
      "List"
    ];
  }
}Copy codeCopy code
import { YourViewModel } from '../viewmodel/YourViewModel';

@Entry
@Component
struct Page {
  private viewModel: YourViewModel = new YourViewModel()

  aboutToAppear(): void {
    const list = this.viewModel.yourList();
  }

  build() {
    RelativeContainer() {
      Text('Hello world');
    }
    .height('100%')
    .width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

  • Page re-renders correctly when state changes
  • Business logic stays isolated from the UI
  • ViewModel can be reused across other pages or components

Limitations or Considerations

  • ViewModel reuse/shared state across components should be handled carefully
  • If not persisted properly, data may be lost between page transitions

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts-state-management-overview

Written by Hatice Akyel

Top comments (0)