效果如图所示:
通过 RegExp 实现对关键词的替换,通过添加 class 实现关键词高亮显示
在查询到结果后执行 changeColor 方法将查询出来的数据传递过来通过 RegExp 来将关键词替换成 html 标签,同时用 vue 中的 v-html 进行绑定。
完整代码展示:
data () {
return {
dropdownList: [],
title: ‘‘,
}
}
methods: { // 模糊搜索 监听事件,当 input 中有内容时,搜索列表显示出来 inputFunc (e) { const params = { q: this.title, } this.title = e.target.value $api.xxx(params).then((res) => { var data = res.data this.changeColor(res.data.data) // 执行 changeColor 方法将查询出来的数据传递过来 if (data.code === 0) { this.dropdownList = data.data if (this.title.length > 0) { this.dropdownListDisplay = true } else { this.dropdownListDisplay = false } } }) },// 实时搜索高亮显示关键词 changeColor (resultsList) { if (resultsList) { resultsList.map((item, index) => { if (this.title && this.title.length > 0) { // 匹配关键字正则 const replaceReg = new RegExp(this.title, ‘g‘) // 高亮替换 v-html 值 const replaceString = ‘<span class="search-text">‘ + this.title + ‘</span>‘ resultsList[index].highlight_title = item.highlight_title.replace( replaceReg, replaceString, ) } }) this.results = [] this.results = resultsList } },
}
原文:https://www.cnblogs.com/Freya0607/p/14738926.html