1,前言
項目中碰到一個需求,搜索數(shù)據(jù)并且關(guān)鍵詞要高亮顯示,接到需求,馬上開干。先上效果圖。源碼已經(jīng)做成了小程序代碼片段,放入了GitHub了,文章底部有源碼鏈接。
2,思路
博主第一時間想到的就是使用split,根據(jù)搜索的關(guān)鍵詞,處理后臺返回的數(shù)據(jù),然后indexOf找到關(guān)鍵字,給每個字添加deep字段,deep為true,則高亮,為false,則正常。由于是小程序,所以樓主直接做成了一個高亮組件,代碼很簡單,實現(xiàn)步驟如下。
3,代碼邏輯
模擬數(shù)據(jù)如下
1
2
3
4
5
6
7
8
9
10
|
list:[ '武漢大學(xué)' , '華中科技大學(xué)' , '華中師范大學(xué)' , '中南財經(jīng)政法大學(xué)' , '中國地質(zhì)大學(xué)' , '武漢理工大學(xué)' , '華中農(nóng)業(yè)大學(xué)' , '武漢科技大學(xué)' , ], |
在data中定義了一個空數(shù)組,用于存放根據(jù)搜索key過濾后的數(shù)據(jù)
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大學(xué)" 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參數(shù)傳遞給組件
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' } } |
組件的初始數(shù)據(jù)
1
2
3
|
data: { highlightList:[], //處理后的數(shù)據(jù) } |
組件的wxml
1
|
< text class = "{{ item.deep ? 'green' : '' }}" wx:for = "{{ highlightList }}" wx:key = "index" >{{ item.val }}</ text > |
組件的高亮數(shù)據(jù)處理
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); } }, /** * 關(guān)鍵字高亮處理 * @param { String } text - 文本 * @param { String } key - 關(guān)鍵字 */ _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
到此這篇關(guān)于微信小程序實現(xiàn)搜索關(guān)鍵詞高亮的示例代碼的文章就介紹到這了,更多相關(guān)小程序搜索關(guān)鍵詞高亮內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/-pdd/p/14592080.html