# 鸿蒙next 带你玩转搜索框组件 Search组件 站点:答源(https://www.dandroid.cn/) 原文:https://www.dandroid.cn/archives/22065 Canonical:https://www.dandroid.cn/archives/22065 作者:admin 发布日期:2024-09-30 最后更新:2024-09-30 01:47 分类:技术方案 内容类型:post 说明:本页是原文的纯文本镜像,供大模型与检索器完整读取;不含导航、广告、付费框。引用请以上方「原文」链接为准。 ## 正文 前言导读 大家在日常开发中肯定会遇到搜索框搜索这种需求,很多同学都会疑惑如何实现,不要着急他来了 Search 组件 今天就用过一个常用案例使用Search 实现搜索功能 请求服务器数据展示来给大家分享 。 Search api使用方法 大家去查阅官网文档即可 本文不讲解这一块 developer.huawei.com/consumer/cn… 效果图 准备工作 具体实现  build() {    Column(){     Row(){       Text('职位')         .fontSize(14)         .fontColor(Color.Black)         .textAlign(TextAlign.Start).margin({ left: 5}) ​       Search({ value: this.changeValue, placeholder: '请输入搜索信息', controller: this.controller })         .searchButton(CommonConstant.SEARCH_TEXT)         .layoutWeight(1)         .margin({ left: 8,right:8})         .backgroundColor($r('app.color.sections_back_bg'))         .onSubmit((vaule:string)=>{           console.log("vaule -- > "+vaule);           this.search(vaule); ​         }).onChange((onChangevalue)=>{ ​         console.log("onChange -- > "+onChangevalue);       })           }.width('100%')     .height(50)     .backgroundColor(Color.White)     .justifyContent(FlexAlign.Start)      this.getlistview(); ​   }.width('100%')   .height('100%') } ​ 我们再使用 Search 组件的时候需要 添加我们 controller 然后去监听我们的 onSubmit 方法和 onChange 方法 onSubmit 是我们点击 searchButton 的时候触发的 onChange 监听搜索框内容变化的方法 @Builder private  getlistview(){  List({space:commonConst.LIST_ITEM_SPACE,scroller:this.scroller}){    ForEach(this.dataList,(item:PositionData)=>{      ListItem() {        Column() {          Row(){            Text(item?.name).fontSize(20).fontWeight(FontWeight.Bold).fontColor(Color.Black) ​            Text(item?.salary).fontSize(16).fontWeight(FontWeight.Bold).fontColor($r('app.color.boss_blue'))         }         .width('100%')         .justifyContent(FlexAlign.SpaceBetween) ​          Text(item?.cname)           .fontSize(14)           .fontWeight(700)           .fontColor('#333')           .width('100%')          Row({space: 5}){            Text('经验不限')             .padding(5)             .borderRadius(2)             .fontSize(10)             .fontColor('#333')             .backgroundColor('#eeeeee')            Text('本科')             .padding(5)             .borderRadius(2)             .fontSize(10)             .fontColor('#333')             .backgroundColor('#eeeeee')            Text('计算机专业')             .padding(5)             .borderRadius(2)             .fontSize(10)             .fontColor('#333')             .backgroundColor('#eeeeee')         }         .width('100%')          Row({space: 10}){            Image($r('app.media.app_icon'))             .height(20)             .width(20)             .borderRadius(10)             .objectFit(ImageFit.Contain)            Text(item?.username)             .fontSize(14)             .width('100%')             .fontColor($r('app.color.boss_blue'))         }       }       .padding(10)       .width('100%')       .backgroundColor(Color.White)       .borderRadius(10)     }   }) }.width(commonConst.GOODS_LIST_WIDTH) .backgroundColor('#eeeeee')   .edgeEffect(EdgeEffect.None) } 搜索请求服务器 在上面UI的 onSubmit 方法里面去调用 search方法请求服务器来展示我们接口返回的数据 async  search(name:string){  let getname:string='name='  let searchurl=CommonConstant.POSITIONLIKE+getname+name  httpRequestGet(searchurl).then((data)=>{    Logger.error("search请求结果=--->"+ data.toString())    let positionModel:PositionModel=JSON.parse(data.toString())    let msg:string=positionModel.msg    if(positionModel.code===200){      this.searchlist=positionModel.data      this.dataList.length=0      this.dataList=[]      this.dataList.push(...this.searchlist)   }else{      prompt.showToast({        message:msg     })   } }) ​ } 初始化请求服务器 async  getpostition(){ ​  let networkurl=CommonConstant.POSITIONALL  httpRequestGet(networkurl).then((data)=>{    Logger.error("职位请求结果=--->"+ data.toString());    let positionModel:PositionModel=JSON.parse(data.toString());    this.JokeList=positionModel.data;    this.dataList.push(...this.JokeList); }); } 网络请求工具类 import http from '@ohos.net.http'; import Logger from './Logger' import Constants, { ContentType } from '../common/Constants'; ​ ​ ​ export function   httpRequestGet(url:string,params?:string){ return httpRequest(url,http.RequestMethod.GET,params); } export function   httpRequestPost(url:string,params?:string){ ​ return httpRequest(url,http.RequestMethod.POST,params); } function httpRequest(url:string ,method:http.RequestMethod,params?:string):Promise{   let httpRequest=http.createHttp();   let responseResult=httpRequest.request(url,{     method:method,     readTimeout:Constants.HTTP_READ_TIMEOUT,     header:{       'Content-Type':ContentType.JSON     },     connectTimeout:Constants.HTTP_READ_TIMEOUT,     extraData:params ​   });   let getjson:string='';   return responseResult.then((value:http.HttpResponse)=>{     Logger.error("请求状态-- >"+value.responseCode);     if(value.responseCode===200){       Logger.error("请求成功");       let result= `${value.result}`;       Logger.error("请求返回数据",JSON.parse(result));       getjson=result;     }else{       getjson='';     }     return getjson;   }).catch(()=>{         httpRequest.destroy();     return '';   }); } 后端代码实现 DAO层代码实现 我们分别写了查询所有数据和模糊查询数据 @Select("select * from position where lower(name)   like lower(concat('%',#{name},'%')) ") public ListgetallPositionLike(@Param("name") String name); ​ ​ @Select("select * from position") public ListgetallPosition(); @Service(value = "positionService") public class PositionServiceImpl implements PositionService {    @Autowired    PositionDao positionDao; ​    @Override    public List getallPositionLike(String name) {        return positionDao.getallPositionLike(name);   } ​    @Override    public List getallPosition() {        return positionDao.getallPosition();   } ​ } contoller层实现 @RequestMapping("/getallpositionlike") public  Object getAllPositionLinit(@RequestParam(value = "name")String name){    List data=positionService.getallPositionLike(name);    Map map=new HashMap();    if(data!=null&&data.size()>0){        map.put("code",200);        map.put("msg","获取数据成功");        map.put("data",data);   }else{        map.put("code",100);        map.put("msg","暂时没有数据");        map.put("data",data);   }    return  map; } ​ ​ ​ @RequestMapping("/getallposition") public  Object getAllPosition(){    List data=positionService.getallPosition();    Map map=new HashMap();    if(data!=null&&data.size()>0){        map.put("code",200);        map.put("msg","获取数据成功");        map.put("data",data);   }else{        map.put("code",100);        map.put("msg","暂时没有数据");        map.put("data",data);   }    return  map; } 鸿蒙next模糊搜索功能整个前后端的代码就全部讲完了,鸿蒙ArkUI端我们主要是监听了onSubmit, 的变化来请求我们服务端来实现我们的搜索功能 ,搜索成功的时候我们需要把 dataList 置空 然后再添加数据即可, 然后去刷新我们的list组件即可。 最后总结: 鸿蒙next AkrUI 里面的 Search 功能还算是比较丰富 的,无论是搜索款内容变化的监听还是, 点击右边搜索按钮的监听都是非常方便直观。我们只需要监听变化的内容然后去请求服务器的接口来实现我们搜索工程即可, 如果有其他的需求方面可以在文章地下留言。老师看到了都会回复的,更多鸿蒙next开发相关知识的学习和交流都可以关注我掘金专栏或者B站的课程。 如果需要学习更多鸿蒙的知识可以关注我B站教程 课程地址 B站课程地址:www.bilibili.com/cheese/play… 项目内容: 1 常用布局组件的学习 2 网络请求工具类封装 3 arkui 生命周期启动流程 4 日志工具类的封装 5 自定义组合组件的封装 6 路由导航跳转的使用 7 本地地数据的缓存 以及缓存工具类的封装 8 欢迎页面的实现 9 登录案例和自动登录效果实现 10 请求网络数据分页上拉加载 下拉刷新的实现 11 list数据懒加载实现 12 webview组件的使用 团队介绍 团队介绍:作者: 坚果派-徐庆 坚果派由坚果等人创建,团队由12位华为HDE以及若干热爱鸿蒙的开发者和其他领域的三十余位万粉博主运营。专注于分享 HarmonyOS/OpenHarmony,ArkUI-X,元服务,仓颉,团队成员聚集在北京,上海,南京,深圳,广州,宁夏等地,目前已开发鸿蒙 原生应用,三方库60+,欢迎进行课程,项目等合作。 --- 由 答源 DAN 底座 1.4.1 生成 · 2026-11-19T09:38:22+00:00