
回复
一、ArkTS状态变量的定义:
在鸿蒙原生开发中,使用ArkTS开发UI的时候,我们可以对UI进行状态变量的绑定,来进行UI渲染
基本结构如下:
@Component
struct MyComponent {
@State count: number = 0;
private increaseBy: number = 1;
build() {
}
}
@Entry
@Component
struct Parent {
build() {
Column() {
// 从父组件初始化,覆盖本地定义的默认值
MyComponent({ count: 1, increaseBy: 2 })
}
}
}
@State count: number = 0;//通过@State修饰绑定的变量会被UI监听,count发生变化时UI也会随之变化。
这是V1的状态管理方法。
首先我们来看V2的状态修饰器:
@ComponentV2 // 装饰器
struct Index { // struct声明的数据结构
build() { // build定义的UI
}
}
通过以上状态变量的修饰,可以弥补状态管理(V1)的短板,状态管理(V1)在复杂数据类型和隔代数据同步方面可能没有状态管理(V2)更好用,所以我们大型复杂数据结构的项目可以使用状态管理(V2),在日常普通项目中使用状态管理(V1)更方便。
一般鸿蒙项目的开发使用MVVM模式;ArkUI采用了Model-View-ViewModel(MVVM)架构模式,
MVVM将应用分为Model、View和ViewModel三个核心部分,实现数据、视图与逻辑的分离。通过这种模式,UI可以随着状态的变化自动更新,无需手动处理,从而更加高效地管理数据和视图的绑定与更新。
常用的状态管理装饰器包括@Local、@Param、@Event、@ObservedV2、@Trace
来看这段代码:
@ObservedV2
export default class TaskListTeamBean {
@Type(TeamBean)
@Trace login: TeamBean[] = [new TeamBean()];
@Type(TeamBean)
@Trace bill: TeamBean[] = [new TeamBean()];
@Type(TeamBean)
@Trace community: TeamBean[] = [new TeamBean()];
@Type(TeamBean)
@Trace game: TeamBean[] = [new TeamBean()];
@Type(TeamBean)
@Trace person: TeamBean[] = [new TeamBean()];
async loadTasks(context: common.UIAbilityContext) {
let taskList = new ListTeamBean(new WholeBean());
await taskList.loadTasks(context);
this.login = taskList.taskWhole.login
this.bill = taskList.taskWhole.bill
this.community = taskList.taskWhole.community
this.game = taskList.taskWhole.game
this.person = taskList.taskWhole.person
}
addTask(newTask: TaskTeamBean): void {
}
removeTask(removedTask: TaskTeamBean): void {
}
}
@Local taskList: TaskListTeamBean = PersistenceV2.connect(TaskListTeamBean, 'TaskList', () => new TaskListTeamBean())!;
private context = getContext(this) as common.UIAbilityContext;
async aboutToAppear() {
this.taskList = PersistenceV2.connect(TaskListTeamBean, 'TaskList', () => new TaskListTeamBean())!;
if (this.taskList.community.length < 2) {
await this.taskList.loadTasks(this.context);
}
}
通过
这就是MVVM模式+状态管理V2的基本框架开发模式。