vue搜索结果关词键词高亮

原理是遍历需要高亮的内容,通过正则匹配替换需要高亮的词

HTML

<template>
  <div>
    <div>
      <input type="text" v-model="keyword">
      <button @click="search()">搜索</button>
      <p v-for="word in list" v-html="word.valueBright"></p>
    </div>
  </div>
</template>

JS

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
          }
        }
      }

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容