鸿蒙应用开发--基于鸿蒙(HarmonyOS)实现 搜索框关键字的增删查改(CRUD)
该方案通过合理利用鸿蒙的响应式编程模型和首选项数据管理,实现了完整的搜索关键词 CRUD 功能。以下是基于鸿蒙(HarmonyOS)实现。:对搜索过滤输入添加防抖。
·
以下是基于鸿蒙(HarmonyOS)实现 搜索框关键字的增删查改(CRUD) 的完整代码方案,包含详细注释和优化实现:
一、功能增强代码(基于原有增删查)
import { preferences } from '@kit.ArkData';
import { common, BusinessError } from '@kit.AbilityKit';
const PREFERENCES_NAME = 'searchKeywords';
const KEY_KEYWORDS = 'keywords';
@Entry
@Component
struct SearchKeywordManager {
@State inputText: string = '';
@State keywordList: string[] = [];
@State editingIndex: number = -1; // 当前编辑的索引
private prefs: preferences.Preferences | null = null;
// 初始化首选项
async aboutToAppear() {
try {
this.prefs = await preferences.getPreferences(getContext(this) as common.UIAbilityContext, PREFERENCES_NAME);
await this.loadKeywords();
} catch (err) {
console.error('首选项初始化失败:', (err as BusinessError).message);
}
}
// 加载关键词
async loadKeywords() {
if (!this.prefs) return;
try {
const saved = await this.prefs.get(KEY_KEYWORDS, '[]');
this.keywordList = JSON.parse(saved) as string[];
} catch (err) {
console.error('加载失败:', (err as BusinessError).message);
}
}
// 保存/更新关键词
async saveOrUpdateKeyword() {
const keyword = this.inputText.trim();
if (!keyword) return;
if (this.editingIndex === -1) {
// 新增(去重)
this.keywordList = [...new Set([keyword, ...this.keywordList])];
} else {
// 修改
this.keywordList[this.editingIndex] = keyword;
this.keywordList = [...this.keywordList]; // 触发UI更新
this.editingIndex = -1;
}
this.inputText = '';
await this.updatePreferences();
}
// 删除关键词
async deleteKeyword(index: number) {
this.keywordList.splice(index, 1);
await this.updatePreferences();
}
// 清空所有
async clearAll() {
this.keywordList = [];
await this.updatePreferences();
}
// 进入编辑模式
enterEditMode(index: number) {
this.editingIndex = index;
this.inputText = this.keywordList[index];
}
// 持久化存储
private async updatePreferences() {
if (this.prefs) {
await this.prefs.put(KEY_KEYWORDS, JSON.stringify(this.keywordList));
await this.prefs.flush();
}
}
build() {
Column() {
// 输入框(复用为新增/编辑框)
TextInput({ text: this.inputText })
.placeholder(this.editingIndex === -1 ? '输入关键词' : '编辑关键词')
.onChange((value: string) => this.inputText = value)
.onSubmit(() => this.saveOrUpdateKeyword())
.margin(10)
// 关键词列表
List({ space: 5 }) {
ForEach(this.keywordList, (item, index) => {
ListItem() {
Row() {
Text(item).fontSize(16)
// 操作按钮组
Row() {
Button('编辑')
.onClick(() => this.enterEditMode(index))
.type(ButtonType.Capsule)
.width(60)
.height(30)
.margin(5)
Button('删除')
.onClick(() => this.deleteKeyword(index))
.type(ButtonType.Capsule)
.width(60)
.height(30)
.backgroundColor(Color.Red)
}
}
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
}
}, item => item)
}
.layoutWeight(1)
// 清空按钮
Button('清空全部')
.onClick(() => this.clearAll())
.width('90%')
.margin(10)
.backgroundColor(Color.Red)
.fontColor(Color.White)
}
.width('100%')
.height('100%')
}
}
二、核心功能解析
1. 增删查改(CRUD)逻辑
| 操作 | 实现方式 | 技术要点 |
|---|---|---|
| 新增 | 输入框回车触发去重保存 | [...new Set([newItem, ...list])] |
| 删除 | 根据索引删除数组项并更新 | splice(index, 1) + 响应式更新 |
| 修改 | 点击编辑按钮回填输入框,提交后更新指定索引 | 通过 editingIndex 标识编辑状态 |
| 查询 | 加载时自动读取首选项数据 | preferences.get() + JSON 反序列化 |
2. UI 交互优化
- 统一输入框:复用同一个输入框进行新增和编辑
- 状态标识:通过
editingIndex区分新增/编辑模式 - 即时反馈:操作后立即刷新列表(响应式编程)
3. 数据持久化流程
[UI操作] → [更新内存数组] → [序列化为JSON] → [写入Preferences] → [触发flush持久化]
三、扩展功能实现
1. 关键词搜索过滤
@State filterText: string = '';
// 过滤后的列表
get filteredList() {
return this.keywordList.filter(item =>
item.toLowerCase().includes(this.filterText.toLowerCase())
);
}
// 在build中添加搜索框
TextInput({ text: this.filterText })
.placeholder('搜索关键词...')
.onChange((value: string) => this.filterText = value)
.margin(10)
2. 操作撤销功能
private history: string[][] = [];
// 保存历史记录
private async updatePreferences() {
if (this.prefs) {
this.history.push([...this.keywordList]); // 记录历史
await this.prefs.put(KEY_KEYWORDS, JSON.stringify(this.keywordList));
await this.prefs.flush();
}
}
// 撤销操作
async undo() {
if (this.history.length > 1) {
this.history.pop(); // 移除当前状态
this.keywordList = [...this.history[this.history.length - 1]];
await this.updatePreferences();
}
}
3. 关键词分类标签
interface KeywordItem {
text: string;
tags: string[];
}
// 修改保存逻辑
async saveOrUpdateKeyword() {
const newItem: KeywordItem = {
text: this.inputText.trim(),
tags: [] // 可添加标签选择逻辑
};
// ...其余逻辑调整
}
四、性能优化建议
-
分页加载:对大量数据使用
LazyForEach分批渲染LazyForEach(this.keywordList, (item, index) => { // 列表项渲染 }, (item, index) => index.toString()) -
防抖处理:对搜索过滤输入添加防抖
private debounceTimer: number = 0; @Watch('filterText') onFilterTextChange() { clearTimeout(this.debounceTimer); this.debounceTimer = setTimeout(() => { // 执行过滤逻辑 }, 300); } -
数据加密:敏感关键词使用
@kit.CipherKit加密存储import { cryptoFramework } from '@kit.CipherKit'; async encryptData(data: string): Promise<string> { const cipher = cryptoFramework.createCipher('AES256|GCM|PKCS7'); // ...执行加密 return encryptedText; }
五、错误处理策略
// 统一错误处理器
function handleError(err: BusinessError, action: string) {
console.error(`${action}失败:`, err.code, err.message);
promptAction.showToast({
message: `${action}失败,请重试`,
duration: 2000
});
}
// 修改保存方法
async saveOrUpdateKeyword() {
try {
// ...原有逻辑
} catch (err) {
handleError(err as BusinessError, this.editingIndex === -1 ? '保存' : '更新');
}
}
总结:
该方案通过合理利用鸿蒙的响应式编程模型和首选项数据管理,实现了完整的搜索关键词 CRUD 功能。关键点包括:
- 状态管理:利用
@State实现数据驱动 UI - 数据持久化:通过 Preferences 保证数据持久存储
- 交互优化:统一输入框减少界面复杂度
- 可扩展性:易于添加搜索过滤、撤销等进阶功能
更多推荐

所有评论(0)