搜索历史全量代码与效果:ArkTS 在 HarmonyOS 的极简实现
2026/8/16 2:34:32 网站建设 项目流程


实例:搜索历史记录(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}from'@kit.AbilityKit';import{promptAction}from'@kit.ArkUI';import{SearchHistoryDao,SearchHistory}from'../../database/SearchHistoryDao';@Entry@Componentstruct SearchHistoryPage{@Statehistories:SearchHistory[]=[];@Statekeyword:string='';privatecontext:common.UIAbilityContext=getContext(this)ascommon.UIAbilityContext;aboutToAppear():void{this.refresh();}asyncrefresh():Promise<void>{try{awaitSearchHistoryDao.initSeedData(this.context);this.histories=awaitSearchHistoryDao.queryAll(this.context);}catch(e){promptAction.showToast({message:`加载失败:${e}`});}}/** 搜索:记录关键词(去重 + 超限淘汰) */asyncdoSearch(kw:string):Promise<void>{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.index===1){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{constd=newDate(ts);constnow=newDate();constsameDay=d.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.keyword=v).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.length===0){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.count>1){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')}}

三、注册与运行

  1. main_pages.json追加"pages/samples/SearchHistoryPage"
  2. Index.ets追加:
    Button('🔍 7 搜索历史记录').fontSize(15).width('70%').onClick(()=>this.getUIContext().getRouter().pushUrl({url:'pages/samples/SearchHistoryPage'}))
  3. 构建验证 →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)→ 极简标签流 UI(7-2)→ UPSERT 与 LIMIT 淘汰(7-3)→ 热词种子(7-4)→ 全量代码(7-5)。核心技术是「唯一约束 + 先查后改 + DELETE IN (SELECT LIMIT)」三件套——这是「有上限的最近记录」的通用数据层答案。极简的 3 字段表和极简的标签流 UI 相得益彰,是「小功能也能讲出数据库门道」的典范。

下一个实例(8 商品分页列表)将引入LIMIT/OFFSET 分页 + 懒加载——大数据量列表的核心能力,UI 是双列瀑布流。

七、核心代码片段补充讲解

1. 搜索框 onChange 实时联动

TextInputonChange在每次输入变化时触发,把输入值同步到状态变量keyword

TextInput({placeholder:'输入关键词搜索…',text:this.keyword}).onChange((v:string)=>this.keyword=v)

@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.count>1){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}`)

关键点:keyGeneratorid-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,点击「搜索」或回车即触发doSearch,Toast 弹出「🔍 搜索「Ark」」,输入→记录→反馈一气呵成。

点击标签回填:点击标签「HarmonyOS 开发」时,该词同时作为输入回填到搜索框(text: this.keyword由状态驱动),并立即发起搜索——「点一下、搜一下」的零成本回搜体验。

过滤动画节奏:标签增删时 ForEach 按 key 最小化 diff——被淘汰的旧词直接移除、新词插入队首,视觉上呈「标签流整体前移一格」的顺滑过渡,无闪烁、无整列重排。

九、代码质量要点补充

关注点本实例做法
输入绑定onChange 单向同步 + @State 单一数据源
列表 keyid-keyword组合键,diff 稳定
条件徽标count > 1才渲染次数角标
删除确认清空走 showDialog、单条长按不打扰
淘汰边界MAX_KEEP 常量 + trim 幂等可重入

十、FAQ

Q1:为什么 TextInput 要绑定text: this.keyword
A:让状态变量成为唯一数据源。搜索成功后如需回填或清空输入框,只需改keyword一个变量,UI 自动刷新,避免多处分叉状态。

Q2:标签流为什么用 Flex 而不是 List?
A:历史词数量少(≤10)且需自动换行,Flex wrap 天然支持「从左到右、放不下换行」的铺排;List 更适合数量大、需滚动的场景,两害相权取轻。

Q3:长按删除为什么不弹确认框?
A:单条删除损失小且可再搜回来,长按本身已是一道防误触门槛,再加确认框反而打断连续操作;清空是全量不可逆操作,才需要二次确认。

Q4:onChange 会触发数据库写入吗?
A:不会。onChange 只更新内存状态keyword,只有点击搜索/回车(doSearch)才落库——输入过程零 IO,性能无压力。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询