搜索历史全量代码与效果:ArkTS 在 HarmonyOS 的极简实现

发布时间:2026/8/16 2:35:03
搜索历史全量代码与效果:ArkTS 在 HarmonyOS 的极简实现 实例搜索历史记录SearchHistory收官文章一、文件清单文件职责行数database/SearchHistoryDao.ets数据层去重插入、LIMIT 淘汰、CRUD、种子约 200 行pages/samples/SearchHistoryPage.etsUI 层标签流 时间线 清空约 150 行resources/base/profile/main_pages.json路由注册pages/samples/SearchHistoryPage追加一行pages/Index.ets首页入口按钮追加一个按钮本篇文章完整展示可编译运行的 SearchHistoryPage 代码最后描述运行效果。二、SearchHistoryPage 完整代码import{common}fromkit.AbilityKit;import{promptAction}fromkit.ArkUI;import{SearchHistoryDao,SearchHistory}from../../database/SearchHistoryDao;EntryComponentstruct SearchHistoryPage{Statehistories:SearchHistory[][];Statekeyword:string;privatecontext:common.UIAbilityContextgetContext(this)ascommon.UIAbilityContext;aboutToAppear():void{this.refresh();}asyncrefresh():Promisevoid{try{awaitSearchHistoryDao.initSeedData(this.context);this.historiesawaitSearchHistoryDao.queryAll(this.context);}catch(e){promptAction.showToast({message:加载失败:${e}});}}/** 搜索记录关键词去重 超限淘汰 */asyncdoSearch(kw:string):Promisevoid{if(!kw.trim()){return;}awaitSearchHistoryDao.addKeyword(this.context,kw);awaitthis.refresh();promptAction.showToast({message: 搜索「${kw.trim()}」});}clearAll():void{promptAction.showDialog({title:清空历史,message:确定清空全部搜索历史吗,buttons:[{text:取消,color:#808080},{text:清空,color:#EF4444},],}).then((res:promptAction.ShowDialogSuccessResponse){if(res.index1){SearchHistoryDao.clearAll(this.context).then(async(){awaitthis.refresh();promptAction.showToast({message: 已清空});});}});}deleteOne(id:number):void{SearchHistoryDao.deleteOne(this.context,id).then(async(){awaitthis.refresh();});}privatefmtTime(ts:number):string{constdnewDate(ts);constnownewDate();constsameDayd.getFullYear()now.getFullYear()d.getMonth()now.getMonth()d.getDate()now.getDate();if(sameDay){return今天${String(d.getHours()).padStart(2,0)}:${String(d.getMinutes()).padStart(2,0)};}return${d.getMonth()1}月${d.getDate()}日;}build(){Column(){// 标题栏 Row(){Column(){Text( 搜索历史).fontSize(22).fontWeight(FontWeight.Bold)Text(保留最近${this.histories.length}条).fontSize(12).fontColor(#999999).margin({top:2})}.alignItems(HorizontalAlign.Start).layoutWeight(1)Text(清空).fontSize(14).fontColor(#EF4444).onClick(()this.clearAll())}.width(100%).padding({left:16,right:16,top:12})// 搜索框 Row({space:8}){TextInput({placeholder:输入关键词搜索…,text:this.keyword}).layoutWeight(1).height(40).backgroundColor(Color.White).borderRadius(20).onChange((v:string)this.keywordv).onSubmit(()this.doSearch(this.keyword))Button(搜索).height(40).backgroundColor(#3B82F6).fontColor(Color.White).onClick(()this.doSearch(this.keyword))}.width(94%).margin({top:12})// 历史标签流 Column(){Text(最近搜索).fontSize(16).fontWeight(FontWeight.Bold)if(this.histories.length0){Column(){Text().fontSize(40)Text(暂无搜索历史).fontSize(14).fontColor(#999999).margin({top:8})}.width(100%).margin({top:40})}else{Flex({wrap:FlexWrap.Wrap}){ForEach(this.histories,(h:SearchHistory){Row({space:6}){Text(h.keyword).fontSize(14)if(h.count1){Text(${h.count}次).fontSize(10).padding({left:5,right:5,top:2,bottom:2}).borderRadius(8).backgroundColor(#DBEAFE).fontColor(#3B82F6)}}.padding({left:14,right:14,top:8,bottom:8}).borderRadius(18).backgroundColor(Color.White).margin({right:8,bottom:8}).onClick(()this.doSearch(h.keyword)).gesture(LongPressGesture().onAction(()this.deleteOne(h.id)))},(h:SearchHistory)${h.id}-${h.keyword})}.width(100%).margin({top:12})}}.width(94%).padding(16).margin({top:12}).alignItems(HorizontalAlign.Start)// 时间线 Column(){Text(搜索时间线).fontSize(16).fontWeight(FontWeight.Bold)ForEach(this.histories,(h:SearchHistory){Row({space:10}){Text(·).fontSize(20).fontColor(#3B82F6)Text(h.keyword).fontSize(14).layoutWeight(1)Text(this.fmtTime(h.searchTime)).fontSize(11).fontColor(#999999)Text(✕).fontSize(14).fontColor(#CCCCCC).onClick(()this.deleteOne(h.id))}.width(100%).padding({top:8,bottom:8})},(h:SearchHistory)t-${h.id})}.width(94%).padding(16).margin({top:12,bottom:24}).alignItems(HorizontalAlign.Start)}.width(100%).height(100%).backgroundColor(#F8FAFC)}}三、注册与运行main_pages.json追加pages/samples/SearchHistoryPageIndex.ets追加Button( 7 搜索历史记录).fontSize(15).width(70%).onClick(()this.getUIContext().getRouter().pushUrl({url:pages/samples/SearchHistoryPage}))构建验证 →BUILD SUCCESSFUL。四、运行效果描述进入「 7 搜索历史记录」第一屏标题栏「 搜索历史 · 保留最近 10 条」右上角红色「清空」圆角搜索框 蓝色「搜索」按钮下方「最近搜索」标签流——10 个白色胶囊标签铺开HarmonyOS 开发×8 蓝色徽标、ArkTS 语法×6、SQLite 实战×5…标签流下方「搜索时间线」——蓝色圆点 关键词 相对时间 ✕。交互一重搜上浮点「HarmonyOS 开发」标签 → Toast「 搜索「HarmonyOS 开发」」→ 该词时间戳刷新、次数 8→9上浮到标签流第一位。交互二新增淘汰输入新词「组件通信」搜索 → 历史变 11 条 → trim 自动淘汰最旧的「弹窗组件」→ 列表保持 10 条新词出现在最前。交互三长按删除长按任意标签 → 该词消失deleteOne列表重排。交互四一键清空点「清空」→ 确认框 → 清空后标签流显示「 暂无搜索历史」空态。五、代码质量要点回顾关注点本实例做法去重keyword UNIQUE 先查后改上限trim 淘汰MAX_KEEP 常量单一来源上浮刷新 search_time ORDER BY DESC清空确认showDialog index 1手势删除LongPressGesture 长按空态 暂无搜索历史六、文章小结实例 7「搜索历史记录」收官。五篇文章覆盖去重建表7-1→ 极简标签流 UI7-2→ UPSERT 与 LIMIT 淘汰7-3→ 热词种子7-4→ 全量代码7-5。核心技术是「唯一约束 先查后改 DELETE IN (SELECT LIMIT)」三件套——这是「有上限的最近记录」的通用数据层答案。极简的 3 字段表和极简的标签流 UI 相得益彰是「小功能也能讲出数据库门道」的典范。下一个实例8 商品分页列表将引入LIMIT/OFFSET 分页 懒加载——大数据量列表的核心能力UI 是双列瀑布流。七、核心代码片段补充讲解1. 搜索框 onChange 实时联动TextInput的onChange在每次输入变化时触发把输入值同步到状态变量keywordTextInput({placeholder:输入关键词搜索…,text:this.keyword}).onChange((v:string)this.keywordv)State keyword是响应式数据源它同时驱动 TextInput 的text属性和后续搜索逻辑。注意单向绑定——text: this.keyword只是初始值真正同步靠 onChange 回调若去掉 onChange输入框将无法输入。2. 热词标签流渲染标签流用Flex({ wrap: FlexWrap.Wrap })ForEach渲染每项是一个白底胶囊ForEach(this.histories,(h:SearchHistory){Row({space:6}){Text(h.keyword).fontSize(14)if(h.count1){Text(${h.count}次).fontSize(10).padding({left:5,right:5,top:2,bottom:2}).borderRadius(8).backgroundColor(#DBEAFE).fontColor(#3B82F6)}}.borderRadius(18).backgroundColor(Color.White).onClick(()this.doSearch(h.keyword)).gesture(LongPressGesture().onAction(()this.deleteOne(h.id)))},(h:SearchHistory)${h.id}-${h.keyword})关键点keyGenerator用id-keyword组合键保证去重后 key 稳定、diff 最小if (h.count 1)条件渲染次数徽标只有搜索多次的词才带蓝色「×N次」小角标。3. 清空历史按钮右上角「清空」走showDialog二次确认res.index 1判断点击的是第二个按钮清空Text(清空).fontSize(14).fontColor(#EF4444).onClick(()this.clearAll())删除类操作一律带确认弹窗避免误触造成不可恢复的数据丢失——这是移动端 UX 的底线。八、运行效果细节输入即同步在搜索框输入「Ark」的瞬间页面并无跳转——onChange已把输入实时写入keyword点击「搜索」或回车即触发doSearchToast 弹出「 搜索「Ark」」输入→记录→反馈一气呵成。点击标签回填点击标签「HarmonyOS 开发」时该词同时作为输入回填到搜索框text: this.keyword由状态驱动并立即发起搜索——「点一下、搜一下」的零成本回搜体验。过滤动画节奏标签增删时 ForEach 按 key 最小化 diff——被淘汰的旧词直接移除、新词插入队首视觉上呈「标签流整体前移一格」的顺滑过渡无闪烁、无整列重排。九、代码质量要点补充关注点本实例做法输入绑定onChange 单向同步 State 单一数据源列表 keyid-keyword组合键diff 稳定条件徽标count 1才渲染次数角标删除确认清空走 showDialog、单条长按不打扰淘汰边界MAX_KEEP 常量 trim 幂等可重入十、FAQQ1为什么 TextInput 要绑定text: this.keywordA让状态变量成为唯一数据源。搜索成功后如需回填或清空输入框只需改keyword一个变量UI 自动刷新避免多处分叉状态。Q2标签流为什么用 Flex 而不是 ListA历史词数量少≤10且需自动换行Flex wrap 天然支持「从左到右、放不下换行」的铺排List 更适合数量大、需滚动的场景两害相权取轻。Q3长按删除为什么不弹确认框A单条删除损失小且可再搜回来长按本身已是一道防误触门槛再加确认框反而打断连续操作清空是全量不可逆操作才需要二次确认。Q4onChange 会触发数据库写入吗A不会。onChange 只更新内存状态keyword只有点击搜索/回车doSearch才落库——输入过程零 IO性能无压力。

相关新闻