这是一个我项目中的截图,但是数据结构又略微有点复杂,不好演示,所以单独又写了一个demo,数据来自干活集中营
实时搜索高亮关键字
关键函数:将字符串使用关键字分割:
//返回一个使用key切割str后的数组,key仍在数组中getHilightStrArray: function(str, key) { return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%'); }
一、新建一个自定义组件,作为显示有高亮字符串的组件
1、在自定义组件wxml中循环数组并判断是否是关键字然后设置不同的class,代码如下:
<view> <text wx:for="{{searchArray}}" wx:key="*this" class="{{item == keyName ? 'highlight' : 'normal' }}">{{item}}</text></view>
2、在自定义组件js中,定义传入key和str的属性对象datas
properties: { /** * {key:'关键字',name:'待匹配字符串'} */ datas: { type: Object, observer: "_propertyDataChange" } },
开始是单独传入key和name,表现正常,但是发现在某些特殊情况得不到想要的结果,这里就不列出来了,有兴趣的朋友可以自己尝试。
3、在自定义组件js中,处理传入的数据
methods: { _propertyDataChange: function(newVal) { console.log(newVal) let searchArray = this.getHilightStrArray(newVal.name, newVal.key) this.setData({ keyName: newVal.key, searchArray: searchArray }) }, getHilightStrArray: function(str, key) { return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%'); } }
自定义组件就此完成了
二、在搜索页面使用
1、在json文件中引入自定义组件
{ "usingComponents": { "searchHighlightTextView": "../../component/searchHighlightTextView/searchHighlightTextView" }, "navigationBarTitleText": "搜索"}
2、在搜索页面wxml中编写input
,和自定义组件searchHighlightTextView
:
<view class="search"> <input focus='auto' bindinput="searchInputAction" placeholder="输入你要搜索的内容" /></view><!-- 搜索时内容 --><view wx:if="{{searchResultDatas.length > 0}}" class="search-content-body"> <block wx:for="{{searchResultDatas}}"> <view class="search-result-item"> <searchHighlightTextView class="result-item" datas='{{searchData[index]}}' bindtap="chooseSearchResultAction" data-id='{{item.ganhuo_id}}' /> </view> </block></view>
3、在搜索页面获取输入内容并请求网络赋值,这里有个关键点我们使用的datas是一个Object,所以在获取到数据中先组searchData
这个Object:
wx.request({ url: 'https://gank.io/api/search/query/' +value + '/category/all/count/10/page/1', data: '', success: function (res) { // console.log(res) let searchData = res.data.results.map(function(res){ return { key: value,name:res.desc} }) that.setData({ searchData, searchResultDatas: res.data.results }) }
作者:韦弦Zhy
链接:https://www.jianshu.com/p/86d73745e01c
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦