vue项目中,模糊搜索结果中关键词高亮,亲测有效

266 阅读1分钟

思路:将关键词每一个字符与查询结果的字段进行比对,命中字符添加标签进行包裹,并添加高亮样式。

<div class="title" v-html="searchResultFilter(data.title)"></div>

searchResultFilter (value) {
      let returnValue = value
      if (returnValue && this.searchKey) {
        let searchKeyList = this.searchKey.split("")
        let valueList = value.split("")
        searchKeyList.map(item => {
          valueList.map((vitem, index) => {
            if (item && vitem && item === vitem) {
              valueList[index] = `<span style='color: #2D8CF0;'>${vitem}</span>`
            }
          })
        })
        returnValue = valueList.join("")
      }
      return returnValue
    }