1# 搜索功能实现案例 2 3### 介绍 4 5本示例介绍使用includes方法对数据实现模糊查询 6 7### 效果图预览 8 9<img src="./entry/src/main/resources/base/media/search_component.gif" width="200"> 10 11**使用说明** 12 131. 点击首页搜索框跳转到搜索页面 142. 在搜索页面输入框中输入搜索的内容,下方列表自动根据搜索的内容进行筛选渲染 153. 点击筛选后的列表跳转到相应的页面 164. 跳转后会保存搜索历史,搜索历史使用持久化存储处理退出应用再次进入依旧存在 175. 点击搜索历史可以跳转到相应页面 18 19### 实现思路 20 211. 通过include方法判读是否存在符合条件的数据。源码参考[SearchPage.ets](./searchcomponent/src/main/ets/components/mainpage/SearchComponent.ets) 22```ts 23 searchFunc(value: string) { 24 let newListData: ListData[] = []; 25 if (this.searchListData !== undefined) { 26 for (let i = 0; i < this.searchListData.length; i++) { 27 // 通过includes对输入的字符进行查询 28 if (this.searchListData[i].name.toLowerCase().includes(value.toLowerCase())) { 29 newListData.push(this.searchListData[i]) 30 } 31 } 32 } 33 this.listData = newListData 34 } 35 ``` 362通过PersistentStorage进行持久化数据存储。源码参考[SearchPage.ets](./searchcomponent/src/main/ets/components/mainpage/SearchComponent.ets) 37```ts 38 PersistentStorage.persistProp('searchHistoryData', []) 39 @StorageLink('searchHistoryData') searchHistoryData: ListData[] = [] 40 ListItem() { 41 Column() { 42 Row() { 43 Image($r('app.media.search')) 44 .width($r('app.string.search_list_image_width')) 45 Text(item.name) 46 .fontSize($r('app.string.search_history_font_size2')) 47 .margin({ left: $r('app.string.search_history_text_padding_margin2') }) 48 } 49 50 Divider() 51 .width('100%') 52 .height(1) 53 .margin({ top: $r('app.string.search_history_text_padding_margin1') }) 54 } 55 .width('100%') 56 .alignItems(HorizontalAlign.Start) 57 } 58 .width('100%') 59 .margin({ top: $r('app.string.search_history_text_padding_margin1') }) 60 .onClick(() => { 61 if (this.searchHistoryData.includes(item)) { 62 return; 63 } 64 // 更新搜索历史数据 65 this.searchHistoryData.push(item); 66 // 调用动态路由相关方法实现页面跳转 67 DynamicsRouter.push(item.routerInfo, item.param); 68 }) 69 ``` 70 71### 高性能知识点 72 73**不涉及** 74 75### 工程结构&模块类型 76 77 ``` 78 SearchComponent // har类型(默认使用har类型,如果使用hsp类型请说明原因) 79 |---model 80 | |---ListData.ets // 筛选数据模型 81 |---SearchComponent.ets // 搜索组件 82 |---SearchPage.ets // 搜索页面 83 ``` 84 85### 模块依赖 86 87**不涉及** 88 89### 参考资料 90 91[search组件详细用法可参考性能范例](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-arkui/arkui-js/js-components-basic-search.md) 92 93### 相关权限 94 95不涉及。 96 97### 依赖 98 99不涉及。 100 101### 约束与限制 102 1031.本示例仅支持标准系统上运行,支持设备:RK3586。 104 1052.本示例为Stage模型,支持API12版本SDK,SDK版本号(API Version 12 Release)。 106 1073.本示例需要使用DevEco Studio版本号(DevEco Studio 5.0.0 Release)及以上版本才可编译运行。 108 109### 下载 110 111如需单独下载本工程,执行如下命令: 112 113```shell 114git init 115git config core.sparsecheckout true 116echo code/UI/SearchComponent/ > .git/info/sparse-checkout 117git remote add origin https://gitee.com/openharmony/applications_app_samples.git 118git pull origin master