鸿蒙PC端Electron开发:数据模型与词汇库设计
在开始编写用户界面之前,先明确数据结构有几个优势:
- 解耦UI和数据 - 页面只关心接收的数据内容,不关注数据来源。
- 易于扩展 - 当前使用硬编码数据,未来可以轻松替换为数据库或网络接口,无需修改UI层。
- 团队协作 - 前后端开发者可以基于相同的接口定义并行工作。
- 类型安全 - ArkTS作为强类型语言,定义好接口后编译器会进行类型检查。
我们的单词学习应用需要管理的信息包括:单词本身(英文、释义、音标)、词根词缀分解(辅助记忆)、学习分组(按日期)以及唯一标识符(用于列表渲染)。
一、定义VocabularyWord数据模型
在electron/src/main/ets/models/目录下创建WordModel.ets文件:
export interface WordComponent {
text: string;
meaning: string;
category: 'prefix' | 'root' | 'suffix';
}
export interface WordInfo {
components: WordComponent[];
}
export interface VocabularyItem {
id: string;
term: string;
definition: string;
pronunciation: string;
phonetic?: string;
wordInfo?: WordInfo;
studyGroup?: string;
}
二、创建词汇仓库
创建electron/src/main/ets/data/WordRepo.ets文件:
import { VocabularyItem } from '../models/WordModel';
export class WordRepository {
private items: VocabularyItem[] = [
{
id: '001',
term: 'electrical',
definition: 'adj. 电的;与电有关的',
pronunciation: '/ɪˈlektrɪkl/',
studyGroup: '3/12',
wordInfo: {
components: [
{ text: 'electr', meaning: '电', category: 'root' },
{ text: 'ical', meaning: '形容词后缀', category: 'suffix' }
]
}
},
// 更多词汇...
];
getItemsByDate(date: string): VocabularyItem[] {
return this.items.filter(item => item.studyGroup === date);
}
getAllItems(): VocabularyItem[] {
return this.items;
}
getItemById(id: string): VocabularyItem | undefined {
return this.items.find(item => item.id === id);
}
getAvailableGroups(): string[] {
const groupSet = new Set<string>();
for (const item of this.items) {
if (item.studyGroup) {
groupSet.add(item.studyGroup);
}
return Array.from(groupSet).sort();
}
}
三、页面中使用数据仓库
示例代码如下:
import { WordRepository } from '../data/WordRepo';
import { VocabularyItem } from '../models/WordModel';
@Entry
@Component
struct HomePage {
private repo: WordRepository = new WordRepository();
@State words: VocabularyItem[] = [];
@State selectedGroup: string = '3/12';
aboutToAppear() {
this.words = this.repo.getItemsByDate(this.selectedGroup);
}
build() {
Column() {
ForEach(this.words, (word: VocabularyItem) => {
Row() {
Text(word.term)
.fontSize(16)
.fontWeight(FontWeight.Medium);
Text(word.definition)
.fontSize(14)
.fontColor('#6B7280');
}
.width('100%')
.padding(12);
}, (word: VocabularyItem) => word.id);
}
}
}