基础搜索模块 Cordova 与 OpenHarmony 混合开发实战
2026/6/1 18:27:52 网站建设 项目流程

📌 概述

基础搜索模块提供了快速搜索喝茶记录的功能。该模块集成了 Cordova 框架与 OpenHarmony 原生能力,实现了高效的全文搜索和实时搜索结果展示。用户可以通过输入关键词快速查找相关的喝茶记录。模块支持按茶叶类型、产地和备注信息搜索,提供了灵活的搜索选项。

🔗 完整流程

第一步:搜索索引构建

当应用启动时,系统会在后台构建搜索索引。索引包含所有记录的茶叶类型、产地、备注等可搜索字段。这个过程在原生层进行,确保搜索性能。

第二步:实时搜索执行

用户在搜索框中输入关键词时,应用会实时执行搜索。搜索会在原生层进行,利用构建好的索引快速返回结果。搜索结果会实时显示在页面上。

第三步:搜索结果展示

搜索完成后,应用会将匹配的记录显示为列表形式。用户可以点击搜索结果查看详细信息或进行其他操作。

🔧 Web 代码实现

HTML 搜索界面

<divid="basic-search-page"class="page"><divclass="page-header"><h1>基础搜索</h1></div><divclass="search-container"><divclass="search-box-large"><inputtype="text"id="search-keyword"class="search-input"placeholder="输入茶叶类型、产地或备注..."><buttonclass="btn-search"onclick="executeSearch()">🔍 搜索</button></div></div><divid="search-results"class="search-results"><!-- 搜索结果动态生成 --></div><divid="search-empty"class="no-data"style="display:none;"><p>未找到匹配的记录</p></div></div>

搜索界面包含一个大的搜索框和搜索按钮。搜索结果区域用于显示匹配的记录。

搜索逻辑实现

asyncfunctionexecuteSearch(){constkeyword=document.getElementById('search-keyword').value.trim();if(!keyword){showToast('请输入搜索关键词','warning');return;}try{// 调用原生搜索constresults=awaitperformSearch(keyword);constresultsContainer=document.getElementById('search-results');constemptyMessage=document.getElementById('search-empty');if(results.length===0){resultsContainer.innerHTML='';emptyMessage.style.display='block';return;}emptyMessage.style.display='none';resultsContainer.innerHTML='';results.forEach(record=>{constresultEl=createSearchResultElement(record);resultsContainer.appendChild(resultEl);});showToast(`找到${results.length}条记录`,'success');// 记录搜索事件if(window.cordova){cordova.exec(null,null,'TeaLogger','logEvent',['search_executed',{keyword:keyword,resultCount:results.length}]);}}catch(error){console.error('Search failed:',error);showToast('搜索失败,请重试','error');}}asyncfunctionperformSearch(keyword){// 从 IndexedDB 搜索constrecords=awaitdb.getAllRecords();constlowerKeyword=keyword.toLowerCase();returnrecords.filter(record=>record.teaType.toLowerCase().includes(lowerKeyword)||record.origin.toLowerCase().includes(lowerKeyword)||(record.notes&&record.notes.toLowerCase().includes(lowerKeyword)));}functioncreateSearchResultElement(record){constdiv=document.createElement('div');div.className='search-result-item';div.dataset.recordId=record.id;constdate=newDate(record.createdAt).toLocaleDateString('zh-CN');conststars='★'.repeat(record.rating)+'☆'.repeat(5-record.rating);div.innerHTML=`<div class="result-main"> <div class="result-title">${record.teaType}</div> <div class="result-meta"> <span>${record.origin}</span> <span>${date}</span> <span>¥${record.price.toFixed(2)}</span> </div> <div class="result-rating">${stars}</div>${record.notes?`<div class="result-notes">${record.notes}</div>`:''}</div> <div class="result-actions"> <button class="btn-icon" onclick="viewRecord(${record.id})" title="查看">👁️</button> <button class="btn-icon" onclick="editRecord(${record.id})" title="编辑">✏️</button> </div>`;returndiv;}// 绑定搜索框回车事件document.addEventListener('DOMContentLoaded',function(){constsearchInput=document.getElementById('search-keyword');if(searchInput){searchInput.addEventListener('keypress',function(e){if(e.key==='Enter'){executeSearch();}});}});

这段代码实现了基础搜索功能。executeSearch()执行搜索操作。performSearch()在 IndexedDB 中进行搜索。createSearchResultElement()创建搜索结果的 DOM 元素。

🔌 OpenHarmony 原生代码

搜索索引管理

// entry/src/main/ets/plugins/SearchIndex.etsexportclassSearchIndex{privateindex:Map<string,number[]>=newMap();buildIndex(records:TeaRecord[]):void{this.index.clear();records.forEach(record=>{// 按茶叶类型索引this.addToIndex(record.teaType,record.id);// 按产地索引this.addToIndex(record.origin,record.id);// 按关键词索引if(record.notes){constkeywords=record.notes.split(/\s+/);keywords.forEach(keyword=>{this.addToIndex(keyword,record.id);});}});hilog.info(0xFF00,'SearchIndex',`Index built with${this.index.size}entries`);}privateaddToIndex(key:string,recordId:number):void{constlowerKey=key.toLowerCase();if(!this.index.has(lowerKey)){this.index.set(lowerKey,[]);}constids=this.index.get(lowerKey);if(ids&&!ids.includes(recordId)){ids.push(recordId);}}search(keyword:string):number[]{constlowerKeyword=keyword.toLowerCase();returnthis.index.get(lowerKeyword)||[];}}interfaceTeaRecord{id:number;teaType:string;origin:string;notes?:string;}

这个类管理搜索索引。buildIndex()构建搜索索引。search()执行搜索操作。

📝 总结

基础搜索模块展示了如何在 Cordova 框架中实现高效的搜索功能。通过 Web 层的用户界面和交互,结合原生层的索引管理和搜索优化,为用户提供了快速的搜索体验。

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

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

立即咨询