
回复
随着鸿蒙生态的不断壮大,越来越多的开发者开始尝试基于 HarmonyOS Next 进行原生应用开发。本文将结合我近期开发的“记事本”项目,分享如何用 ArkTS 语言和鸿蒙原生组件,打造一款简洁高效的本地记事应用。
本项目参考了小知天气:HarmonyOS Next 气象应用开发实践和HarmonyOS Next智能聊天助手开发实践的架构与美化思路,力求在体验和代码结构上做到极致简洁与易维护。
源码获取:公众号:知识浅谈 回复 记事本源码
效果展示:
├─entry
│ ├─src/main/ets/pages/ # 页面
│ ├─src/main/ets/model/ # 数据模型
│ ├─src/main/ets/service/ # 业务服务
│ └─resources/base/media/ # 图标资源
export class NoteItem {
id: string = '';
title: string = '';
content: string = '';
createTime: string = '';
updateTime: string = '';
constructor() {
this.id = this.generateId();
const now = new Date().toISOString();
this.createTime = now;
this.updateTime = now;
}
private generateId(): string {
return 'note_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
}
说明:
import dataPreferences from '@ohos.data.preferences';
import { NoteItem } from '../model/NoteItem';
export class NoteService {
// ...省略部分代码
async getAllNotes(): Promise<NoteItem[]> {
await this.init();
if (!this.preferences) {
throw new Error('Preferences not initialized');
}
const notesJson: string = await this.preferences.get(NoteService.NOTES_KEY, '[]') as string;
const notes: NoteItem[] = JSON.parse(notesJson);
return notes.sort((a: NoteItem, b: NoteItem) =>
new Date(b.updateTime).getTime() - new Date(a.updateTime).getTime()
);
}
// ...省略其他CRUD方法
}
说明:
@Entry
@Component
struct NoteList {
@State notes: NoteItem[] = [];
private noteService: NoteService = new NoteService();
// 页面每次显示时自动刷新
onPageShow() {
this.loadNotes();
}
async loadNotes(): Promise<void> {
this.notes = await this.noteService.getAllNotes();
}
build() {
Column() {
// ...UI结构略
}
}
}
说明:
@State
修饰 notes,保证数据变化自动驱动UI刷新。onPageShow
是鸿蒙 ArkTS 的页面生命周期钩子,每次页面显示都会调用,非常适合做“返回自动刷新”。@Entry
@Component
struct NoteEdit {
@State note: NoteItem = new NoteItem();
private noteService: NoteService = new NoteService();
private noteId: string = '';
aboutToAppear(): void {
const params: Record<string, string> = router.getParams() as Record<string, string>;
if (params && params['noteId']) {
this.noteId = params['noteId'];
this.loadNote();
}
}
async saveNote(): Promise<void> {
if (this.noteId) {
await this.noteService.updateNote(this.note);
} else {
await this.noteService.createNote(this.note);
}
router.back(); // 返回列表页
}
build() {
// ...UI结构略
}
}
说明:
现象:
在 NoteEdit.ets 保存笔记后返回 NoteList.ets,发现新建或修改的笔记没有立即显示,必须手动重启页面才会刷新。
原因分析:
aboutToAppear
只在页面首次进入时触发,router.back()
返回不会再次触发。最佳实践解决方案:
onPageShow
生命周期钩子。该钩子每次页面显示(包括返回时)都会自动触发,非常适合做数据刷新。代码实现:
onPageShow() {
this.loadNotes();
}
只需在 NoteList.ets 组件内加上该钩子,配合原有的 loadNotes 方法即可。
参考资料:
欢迎大家留言交流 HarmonyOS Next 应用开发经验!