HarmonyOS应用开发入门:从基本结构到状态管理实战指南
前言
(约300字,说明HarmonyOS的发展前景,应用开发的市场需求,以及本教程的核心价值。强调手把手教学特点,降低学习门槛)
一、HarmonyOS应用基本结构解析
1.1 项目目录结构详解
bash
MyFirstApp/
├── AppScope/ # 全局资源
│ ├── resources/
│ └── app.json5 # 应用配置
├── entry/ # 主模块
│ ├── src/main/
│ │ ├── ets/ # 业务代码
│ │ ├── resources/ # 模块资源
│ │ └── module.json5
└── features/ # 可选功能模块
对比传统Android项目结构,突出AppScope
的全局资源管理特性,解释entry
模块的入口意义
1.2 Ability的核心作用
typescript
// EntryAbility.ts
export default class EntryAbility extends Ability {
onCreate() {
// 初始化操作
}
onWindowStageCreate(windowStage: window.WindowStage) {
// 加载首页
windowStage.loadContent("pages/IndexPage", (err) => {
if (err.code) {
// 错误处理
}
});
}
}
通过实际代码演示Ability生命周期,重点说明WindowStage
与页面加载的关系
1.3 页面文件组织结构
bash
pages/
├── IndexPage.ets # 页面逻辑
├── IndexPage.css # 样式文件
└── IndexPage.json # 页面配置
结合MVVM模式讲解三者协同工作原理,演示数据绑定的基础实现
二、页面导航实战演练
(核心功能模块,约1000字)
2.1 路由配置基础
json5
// module.json5
"pages": [
"pages/IndexPage",
"pages/DetailPage"
]
强调路由注册的重要性,演示动态路由注册的进阶用法
2.2 页面跳转六种方式
typescript
// 基础跳转
router.pushUrl({
url: "pages/DetailPage"
})
// 带参跳转
router.pushUrl({
url: "pages/DetailPage?itemId=123"
})
// 带回调跳转
router.pushUrl({
url: "pages/DetailPage"
}).then(() => {
// 跳转成功处理
})
每种方式配合实际应用场景说明(电商商品详情跳转、表单提交跳转等)
2.3 导航栏开发实战
typescript
// 自定义导航栏
@Entry
@Component
struct NavDemo {
@State currentIndex: number = 0
build() {
Column() {
// 导航按钮
Row() {
Button('首页').onClick(() => this.switchTab(0))
Button('我的').onClick(() => this.switchTab(1))
}
// 内容区域
Swiper() {
HomePage()
MinePage()
}
}
}
private switchTab(index: number) {
this.currentIndex = index
}
}
完整实现带滑动效果的Tab导航,包含状态联动与动画优化
三、状态管理深度解析
3.1 状态管理全景图
graph TD
A[状态类型] --> B[页面级状态]
A --> C[应用级状态]
B --> D[@State]
C --> E[AppStorage]
C --> F[LocalStorage]
通过图示清晰划分状态管理层次,说明各方案的适用场景
3.2 页面级状态实战
typescript
@Entry
@Component
struct CounterPage {
@State count: number = 0
build() {
Column() {
Text(`点击次数: ${this.count}`)
.fontSize(20)
Button("增加")
.onClick(() => {
this.count++
})
}
}
}
扩展实现双向绑定、状态监听等进阶功能
3.3 全局状态管理方案
typescript
// 定义全局状态
AppStorage.SetOrCreate<number>('globalCount', 0)
// 在组件中使用
@Component
struct GlobalCounter {
@StorageLink('globalCount') count: number
build() {
Button(`全局计数: ${this.count}`)
.onClick(() => this.count++)
}
}
对比LocalStorage与AppStorage的差异,演示跨页面状态同步
3.4 状态持久化实践
typescript
// 使用Preferences存储
import preferences from '@ohos.data.preferences'
async function saveData(key: string, value: preferences.ValueType) {
const pref = await preferences.getPreferences(this.context)
await pref.put(key, value)
await pref.flush()
}
结合本地存储实现状态持久化,确保应用重启后数据不丢失
四、综合项目实战:TODO应用
- 项目功能规划:添加任务、分类展示、状态切换
- 技术点整合:
- 使用@State管理任务列表
- 通过路由实现详情页跳转
- 应用AppStorage实现主题切换
- 关键代码片段展示:
typescript
@Entry
@Component
struct TodoApp {
@StorageLink('theme') currentTheme: string = 'light'
@State todos: TodoItem[] = []
build() {
Column() {
ThemeSwitcher()
TodoList()
AddButton()
}
}
}
五、调试与优化技巧
(约300字,提升内容实用价值)
- 开发者模式开启指南
- 常用调试命令:
bash
hdc shell
bm get -u
- 性能优化建议:减少不必要的状态更新、合理使用组件复用