直接跳到内容

View 规范

职责说明

View 只负责渲染与布局,不直接发起请求或处理业务逻辑。状态与操作全部来自 ViewModel。

推荐写法

  • 使用 @ComponentV2 声明组件。
  • 通过 @Local 持有 ViewModel 实例。
  • 页面内容拆成 @Builder 方法,便于复用与阅读。
  • 页面标题、返回逻辑统一使用 AppNavDestination

示例

下面示例展示 View 与 ViewModel 的配合方式,注意二者分开维护。

View

ts
import { ColumnCenter } from "designsystem";
import { AppNavDestination } from "ui";
import ProfileViewModel from "../viewmodel/ProfileViewModel";

/**
 * @file 个人信息页视图
 */
@ComponentV2
export struct ProfilePage {
  /**
   * 个人信息页 ViewModel
   */
  @Local
  private vm: ProfileViewModel = new ProfileViewModel();

  /**
   * 构建个人信息页
   * @returns {void} 无返回值
   */
  build(): void {
    AppNavDestination({
      title: $r("app.string.profile_title"),
      viewModel: this.vm
    }) {
      this.ProfileContent();
    };
  }

  /**
   * 构建页面内容
   * @returns {void} 无返回值
   */
  @Builder
  private ProfileContent(): void {
    ColumnCenter() {
      Text(this.vm.nickName);
    };
  }
}

ViewModel

ts
import { BaseViewModel } from "base";

/**
 * @file 个人信息页 ViewModel
 */
@ObservedV2
export default class ProfileViewModel extends BaseViewModel {
  /**
   * 昵称
   */
  @Trace
  nickName: string = "Joker.X";
}

注意事项

  • View 不直接访问仓库或网络,只调用 ViewModel 暴露的方法。
  • 能用组件抽离的 UI 放到 component/,避免在单页堆叠过多代码。