小程序實現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]
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章