用正则来匹配关键词,匹配到的就替换如下
this.list[i].valueBright = this.list[i].value.replace(replaceReg, `<span style="color:#e5242b">${this.keyword}</span>`)
显示的时候要用 v-html 来显示
<p v-for="word in list" v-html="word.valueBright"></p>
完整代码
<div>
<input type="text" v-model="keyword">
<button @click="search()">搜索</button>
<p v-for="word in list" v-html="word.valueBright"></p>
</div>
data() {
return {
keyword:'',
list:[]
}
},
methods:{
search() {
this.list = [ //后台返回的数据
{ id:1,value:'lm' },
{ id:2,value:'LM' },
{ id:3,value:'xx' },
]
const replaceReg = new RegExp(this.keyword, 'ig')
const upperCase = /^[A-Z]+$/ //英文搜索时
for (const i in this.list) {
if (replaceReg.test(this.list[i].value)) {
this.list[i].value.match(replaceReg).map(item => {//可能有多个和关键词一样
if (upperCase.test(item)) {//不区分大小写:如果是大写的就转成大写的,如果搜索区分大小写就不用这个了
this.list[i].valueBright = this.list[i].value.replace(replaceReg, `<span style="color:#e5242b">${this.keyword.toUpperCase()}</span>`)
} else {
this.list[i].valueBright = this.list[i].value.replace(replaceReg, `<span style="color:#e5242b">${this.keyword}</span>`)
}
})
} else {
this.list[i].valueBright = this.list[i].value
}
}
}
}
或者:
// 循环出来的数据
<div
v-html="brightenKeyword(item.keyword)"
class="g-f-l item-r">
</div>
methods:
// 搜索词高亮
brightenKeyword(val) {
try {
const replaceReg = new RegExp(this.keyword, 'ig')
if (val && replaceReg.test(val)) {
val = val.replace(replaceReg, `<span style="color:#e5242b">${this.keyword}</span>`)
}
return val && val.toString().toUpperCase()
} catch (e) {
console.log(e)
return val
}
}
网友评论