场景
前端实现查询后,将过滤后数据中的搜索词展现为高亮。
代码
思路:利用 正则表达式 对过滤词添加类名,然后使用 v-html 渲染在表格中。
// 复制json数组
copyObjectDataList(arr) {
let list = [];
_.each(arr,item => {
list.push({
...item})
})
return list;
},
// 话术内容中的搜索词显示高亮
getHighlightOfText(text, tipSearchTxt) {
let result;
if (tipSearchTxt === '') {
return text;
} else {
let reg = new RegExp(tipSearchTxt, 'g');
result = text.replace(reg, '<span class="bgc-yellow">' + tipSearchTxt + '</span>');
return result;
}
},
// 搜索话术内容
onTipSearchClick(tipSearchTxt) {
// tipCopyList: 复制原数组,存储全部数据
let tipCopyList = this. copyObjectDataList(this.tipCopyList);
if (tipSearchTxt === '') {
this.tipList = tipCopyList;
return;
}
// 筛选带有关键词的数据
this.tipList = tipCopyList.filter(item => {
if (item['tip_title'].indexOf(tipSearchTxt) !== -1 || item['tip_content'].indexOf(tipSearchTxt) !== -1 || item['remark'].indexOf(tipSearchTxt) !== -1) {
if (item['tip_title'].indexOf(tipSearchTxt) !== -1) {
item['tip_title'] = this.getHighlightOfText(item['tip_title'], tipSearchTxt);
}
if (item['tip_content'].indexOf(tipSearchTxt) !== -1) {
item['tip_content'] = this.getHighlightOfText(item['tip_content'], tipSearchTxt);
}
if (item['remark'].indexOf(tipSearchTxt) !== -1) {
item['remark'] = this.getHighlightOfText(item['remark'], tipSearchTxt);
}
return true
}
})
}