1,前言
項目中碰到一個需求,搜索數據并且關鍵詞要高亮顯示,接到需求,馬上開干。先上效果圖。源碼已經做成了小程序代碼片段,放入了GitHub了,文章底部有源碼鏈接。
2,思路
博主第一時間想到的就是使用split,根據搜索的關鍵詞,處理后臺返回的數據,然后indexOf找到關鍵字,給每個字添加deep字段,deep為true,則高亮,為false,則正常。由于是小程序,所以樓主直接做成了一個高亮組件,代碼很簡單,實現步驟如下。
3,代碼邏輯
模擬數據如下
1
2
3
4
5
6
7
8
9
10
|
list:[ '武漢大學' , '華中科技大學' , '華中師范大學' , '中南財經政法大學' , '中國地質大學' , '武漢理工大學' , '華中農業大學' , '武漢科技大學' , ], |
在data中定義了一個空數組,用于存放根據搜索key過濾后的數據
1
|
filterList:[], //過濾后的 |
搜索的wxml和方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// wxml <view class= "search_box" > <input type= "text" placeholder= "請輸入武漢的985/211大學" bindinput= "searchValue" class= "search" /> </view> // 搜索方法 searchValue(e){ let val = e.detail.value; this .setData({ value:val }) if (val.length > 0){ this .setData({ filterList:[] }) let arr = []; for (let i = 0;i < this .data.list.length;i++){ if ( this .data.list[i].indexOf(val) > -1){ arr.push( this .data.list[i]) } } this .setData({ filterList: arr }) } else { this .setData({ filterList: [] }) } } |
定義了一個高亮組件highlight
1
2
3
|
"usingComponents" : { "highlight" : "../../components/highlight/highlight" } |
在頁面中將搜索出來的每一項item和key參數傳遞給組件
1
2
3
|
< view class = "list_li" wx:for = "{{ filterList }}" wx:key = "index" data-index = "{{ index }}" bindtap = "pitchOn" > < highlight text = "{{ item }}" key = "{{ value }}" /> </ view > |
在組件中接收
1
2
3
4
5
6
7
8
|
properties: { text:String, key:{ type:String, value: '' , observer: '_changeText' } } |
組件的初始數據
1
2
3
|
data: { highlightList:[], //處理后的數據 } |
組件的wxml
1
|
< text class = "{{ item.deep ? 'green' : '' }}" wx:for = "{{ highlightList }}" wx:key = "index" >{{ item.val }}</ text > |
組件的高亮數據處理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// 非空過濾 _changeText(e){ if (e.length > 0 && this .properties.text.indexOf(e) > -1){ this ._filterHighlight( this .properties.text, e); } }, /** * 關鍵字高亮處理 * @param { String } text - 文本 * @param { String } key - 關鍵字 */ _filterHighlight(text, key){ let textList = text.split( "" ); let keyList = key.split( "" ); let list = []; for (let i = 0;i < textList.length;i++){ let obj = { deep: false , val:textList[i] } list.push(obj); }; for (let k = 0;k < keyList.length;k++){ list.forEach(item => { if (item.val === keyList[k]){ item.deep = true ; } }) } this .setData({ highlightList:list }) } |
源碼GitHub地址:https://github.com/pdd11997110103/ComponentWarehouse
到此這篇關于微信小程序實現搜索關鍵詞高亮的示例代碼的文章就介紹到這了,更多相關小程序搜索關鍵詞高亮內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/-pdd/p/14592080.html