小程序实现v-html,将搜索结果中搜索的文字标记

在小程序中做搜索功能时,有需求要将搜索的文字标记为蓝色。

小程序实现v-html,将搜索结果中搜索的文字标记

实现方式:

1.使用小程序组将rich-text,将内容用正则匹配并用<span style="color:#1D57D8">${this.inputValue}</span>替换

<rich-text :nodes="item.articleLabel"></rich-text>

 

i.categoryLabel = this.setColor(i.categoryName)

 

setColor(str) {
    let s = `<span style="color:#1D57D8">${this.inputValue}</span>`
    let text = str.replace(new RegExp(this.inputValue,'g'),s)
    return text
}

 

2.使用text,将内容用搜索的文字分割,这个方法可以对标记的内容添加事件。

<text v-if="it.descLabel[0]">{{it.descLabel[0]}}</text>
<text style="color:#1D57D8" @click="goProduct(it.pbId)">{{it.keyword}}</text>
<text v-if="it.descLabel[1]">{{it.descLabel[1]}}</text>

 

x.descLabel = this.setColor('- '+x.description,x.keyword)

 

setColor(str,key) {
    let s1 = str.split(key)[0]
    let s2 = str.split(key)[1]
    return [s1,s2]
}