搜索对应字段(关键字)高亮

模拟 下面的每一行都是搜索返回的文章或者别的什么 搜索的字段有了别的样式

搜索对应字段(关键字)高亮_第1张图片

用 正则的话 要是输入的是特殊字符可能会出现问题

<template>
  <div>
    <input type="text" v-model="inputValue" />
    <button @click="search">点我搜索</button>

      <h3 v-html="res.list[0].title"></h3>
      <h3 v-html="res.list[1].title"></h3>
      <h3 v-html="res.list[2].title"></h3>
      <h3 v-html="res.list[3].title"></h3>

  </div>
</template>
<script>
export default {
     
  name: 'home',
  data () {
     
    return {
     
      // 输入框内容
      inputValue: '',
      // 模仿服务器返回的数据
      res: {
     
        list: [
          {
      title: '这是一个寂寞的天' },
          {
      title: '下着有些伤心的雨' },
          {
      title: '精油开背大保健' },
          {
      title: '巧克力炖土豆蜜汁烤榴莲' }
        ]
      },
    }
  },
  methods: {
     
  // 搜索事件
    search () {
     
      // 恢复数据
      this.res = {
     
        list: [
          {
      title: '这是一个寂寞的天' },
          {
      title: '下着有些伤心的雨' },
          {
      title: '精油开背大保健' },
          {
      title: '巧克力炖土豆蜜汁烤榴莲' }
        ]
      }
      // 将title里面相关字段替换输入框关键字 
      const _reg = new RegExp(this.inputValue, 'g')
      this.res.list.forEach(item => {
     
        item.title = item.title.replace(
          _reg,
          `${
       this.inputValue}`
        )
      })
    }
  }
}
</script>

结果

正常功能是可以实现的

搜索对应字段(关键字)高亮_第2张图片搜索对应字段(关键字)高亮_第3张图片

加入特殊字符就会出现问题了

自己测试出了 \ * + | 会触发 ( | 的效果尤为灵性)

搜索对应字段(关键字)高亮_第4张图片搜索对应字段(关键字)高亮_第5张图片

split()/join()配合使用 (没发现有bug)

 // 搜索内容不为空 才进行替换
  if (this.inputValue.trim() !== '') {
     
     // 搜索字体高光
     this.res.list.forEach(item => {
     
       // 用搜索框的内容 来把标题分割成 数组
       const _arr = item.title.split(this.inputValue)
          // 用 添加了样式 的内容来接成字符串
       item.title = _arr.join(
           `${
       this.inputValue}`
       )
     })
 }

效果实现没问题 中间插入特殊字符是不会匹配的

搜索对应字段(关键字)高亮_第6张图片搜索对应字段(关键字)高亮_第7张图片

你可能感兴趣的:(渲染,javascript,css)