业务状态
介绍
业务状态模块(biz_state)管理与业务相关的全局状态,如用户信息、购物车等。它与 core/state 的框架级状态(断点、安全区)分离,保持职责清晰。
与 core/state 的区别
| 模块 | 内容 | 示例 |
|---|---|---|
| core/state | 框架级状态,与业务无关 | BreakpointState、WindowSafeAreaState |
| foundation/biz_state | 业务状态 | UserState、DemoCounterState |
状态定义示例
用户状态
文件位置:foundation/biz_state/src/main/ets/UserState.ets
ts
import { PersistenceV2 } from "@kit.ArkUI";
/**
* @file 用户状态(持久化)
*/
export const USER_STATE_KEY: string = "user_state";
@ObservedV2
export class UserState {
/**
* 是否已登录
*/
@Trace
isLoggedIn: boolean = false;
/**
* 用户 ID
*/
@Trace
userId: string = "";
/**
* 用户名
*/
@Trace
username: string = "";
/**
* 头像
*/
@Trace
avatar: string = "";
/**
* 设置登录状态
*/
setLoggedIn(userId: string, username: string, avatar?: string): void {
this.isLoggedIn = true;
this.userId = userId;
this.username = username;
this.avatar = avatar ?? "";
}
/**
* 清除登录状态
*/
logout(): void {
this.isLoggedIn = false;
this.userId = "";
this.username = "";
this.avatar = "";
}
}
/**
* 获取用户状态实例(持久化)
*/
export function getUserState(): UserState {
return PersistenceV2.connect<UserState>(
UserState,
USER_STATE_KEY,
() => new UserState()
)!;
}计数器状态
文件位置:foundation/biz_state/src/main/ets/DemoCounterState.ets
ts
import { AppStorageV2 } from "@kit.ArkUI";
/**
* @file 全局计数器状态(临时)
*/
export const DEMO_COUNTER_KEY: string = "demo_counter_state";
@ObservedV2
export class DemoCounterState {
/**
* 当前计数
*/
@Trace
count: number = 0;
/**
* 计数加一
*/
increment(step: number = 1): void {
this.count += step;
}
/**
* 计数减一
*/
decrement(step: number = 1): void {
if (this.count - step < 0) {
this.count = 0;
return;
}
this.count -= step;
}
/**
* 重置计数
*/
reset(resetValue: number = 0): void {
this.count = resetValue;
}
}
/**
* 获取计数器状态实例(临时)
*/
export function getDemoCounterState(): DemoCounterState {
return AppStorageV2.connect<DemoCounterState>(
DemoCounterState,
DEMO_COUNTER_KEY,
() => new DemoCounterState()
)!;
}使用示例
在 ViewModel 中使用
ts
import { UserState, getUserState } from "@foundation/biz-state";
import { DemoCounterState, getDemoCounterState } from "@foundation/biz-state";
@ObservedV2
export default class ProfileViewModel extends BaseViewModel {
/**
* 用户状态
*/
@Trace
userState: UserState = getUserState();
/**
* 计数器状态
*/
@Trace
counterState: DemoCounterState = getDemoCounterState();
/**
* 退出登录
*/
logout(): void {
this.userState.logout();
}
/**
* 增加计数
*/
increment(): void {
this.counterState.increment();
}
}AppStorageV2 与 PersistenceV2
- AppStorageV2:应用全局 UI 状态存储,适合临时状态,应用退出后清除。
- PersistenceV2:持久化存储 UI 状态,适合用户信息等需要保留的数据。
官方文档:
如何新增业务状态
- 在
foundation/biz_state/src/main/ets/下新建状态类。 - 使用
@ObservedV2装饰类。 - 需要响应更新的字段加
@Trace。 - 根据是否需要持久化选择
AppStorageV2.connect或PersistenceV2.connect。 - 在
Index.ets中导出状态类和获取方法。
注意事项
- 只有标注
@Trace的字段才会触发 UI 响应更新。 - 临时状态用 AppStorageV2,需要持久化的状态用 PersistenceV2。
- 状态类中只放状态相关的方法,复杂业务逻辑放在 ViewModel 中。