有一個需求是在已有列表中搜索關鍵詞,然后在列表中展示含有相關關鍵字的數據項並且對關鍵字進行高亮顯示,所以該需求需要解決的就兩個問題:
1.搜索關鍵詞過濾列表數據
2.每個列表高亮關鍵字
ps: 此問題基於數組對象,其他數據類型也可參考此思路。
關鍵詞搜索:過濾數據很簡單,無非就是監聽search,對源數據過濾即可,貼一下代碼:
1 const search = this.search 2 if (search) { 3 this.showdata = this.copyshowdata.filter(data => { 4 return Object.keys(data).some(key => { 5 return String(data[key]).indexOf(search) > -1 6 }) 7 }) 8 } else { 9 this.showdata = this.copyshowdata 10 }
showdata是展示在頁面的,copyshowdata是showdata副本,還原列表時使用的,對其不做任何處理。
上面是使用watch監聽search值變化處理的,也可以使用computed屬性計算showdata。
高亮關鍵字:思路是遍歷showdata,對每一項item的值進行正則匹配(也可匹配指定項),使用<span class="highlights-text"></span> 替換掉search
1 highlights () { 2 const search = this.search 3 this.showdata = this.showdata.map(item => { 4 for (let key in item) { 5 if (key === 'Issuecontent') { 6 let replaceReg = new RegExp(search, 'g')// 匹配關鍵字正則 7 let replaceString = '<span class="highlights-text">' + search + '</span>' // 高亮替換v-html值 8 item[key + '-highlights'] = item[key].replace(replaceReg, replaceString) // 開始替換 9 } 10 } 11 return item 12 }) 13 }
頁面上則使用v-html=“item[key-highlights]”渲染
渲染之后還需要對樣式進行單獨處理,不能加在父類上面,而且scope要去掉,否則樣式不會生效。
1 <style lang="scss"> 2 .highlights-text { 3 color: #ff5134; 4 } 5 </style>
貼一張效果圖: