首页 > 其他 > 详细

vue 实时搜索高亮显示关键字

时间:2021-05-07 19:10:11      阅读:34      评论:0      收藏:0      [点我收藏+]

效果如图所示:

技术分享图片

 

 

 

通过 RegExp 实现对关键词的替换,通过添加 class 实现关键词高亮显示

在查询到结果后执行 changeColor 方法将查询出来的数据传递过来通过 RegExp 来将关键词替换成 html 标签,同时用 vue 中的 v-html 进行绑定。

完整代码展示:


  <input
  v-model="title"
  type="text"
  placeholder="请输入标题"
  @input="inputFunc"
  />
data () {
  return {
    dropdownList: [],
    title: ‘‘,
  }
}
methods: {
    // 模糊搜索 监听事件,当 input 中有内容时,搜索列表显示出来
    inputFunc (e) {
      const params = {
        q: this.title,
      }
      this.title = e.target.value
      $api.xxx(params).then((res) => {
        var data = res.data
        this.changeColor(res.data.data) // 执行 changeColor 方法将查询出来的数据传递过来
        if (data.code === 0) {
          this.dropdownList = data.data
          if (this.title.length > 0) {
            this.dropdownListDisplay = true
          } else {
            this.dropdownListDisplay = false
          }
        }
      })
    },// 实时搜索高亮显示关键词
    changeColor (resultsList) {
      if (resultsList) {
        resultsList.map((item, index) => {
          if (this.title && this.title.length > 0) {
            // 匹配关键字正则
            const replaceReg = new RegExp(this.title, g)
            // 高亮替换 v-html 值
            const replaceString =
              <span class="search-text"> + this.title + </span>
            resultsList[index].highlight_title = item.highlight_title.replace(
              replaceReg,
              replaceString,
            )
          }
        })
        this.results = []
        this.results = resultsList
      }
    },
}

 

vue 实时搜索高亮显示关键字

原文:https://www.cnblogs.com/Freya0607/p/14738926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!