vue需求:模糊查询,并且高亮,希望搜索一句话中任意的词,都可以搜索到,

需求:模糊查询,并且高亮,希望搜索一句话中任意的词,都可以搜索到,
需求1举例:比如搜索西,搜索到所有带西的句子,
需求2举例: 搜索西大,可以查询到带有西或者大的句子,并且全部高亮。


<template>
  <div>
    <input v-model="keyword" placeholder="请输入搜索关键字">
    <ul>
      <li v-for="(item, index) in filteredData" :key="index" v-html="highlight(item.text)"></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      data: [
        { text: '西安的城墙很大。' },
        { text: '西安交通大学是一所985高校。' },
        { text: '我喜欢吃西瓜。' },
        { text: '这是一份西式菜谱。' }
      ]
    }
  },
  computed: {
    filteredData() {
      const pattern = new RegExp(this.keyword.split(/\s+/).join('.*'), 'gi');
      return this.data.filter(item => pattern.test(item.text));
    }
  },
  methods: {
    highlight(text) {
      const pattern = new RegExp(this.keyword.split(/\s+/).join('|'), 'gi');
      return text.replace(pattern, '<span style="color: red">$&</span>');
    }
  }
}
</script>
<template>
  <div>
    <input v-model="keyword" @input="search" placeholder="请输入关键词">
    <ul>
      <li v-for="(item, index) in searchResult" :key="index">
        <p v-html="highlight(item)"></p>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      sourceData: [
        '西风吹老洞庭波,一夜湘君白发多',
        '月落乌啼霜满天,江枫渔火对愁眠',
        '大漠孤烟直,长河落日圆',
        '黄沙百战穿金甲,不破楼兰终不还',
        '故人具鸡黍,邀我至田家',
        '重阳节到处飘香,采菊东篱下',
        '青山遮不住,毕竟东流去'
      ]
    }
  },
  computed: {
    // 搜索结果
    searchResult() {
      const reg = new RegExp(this.keyword, 'gi') // 忽略大小写的正则表达式
      return this.sourceData.filter(item => reg.test(item))
    }
  },
  methods: {
    // 高亮匹配的关键词
    highlight(str) {
      return str.replace(new RegExp(this.keyword, 'gi'), `<span style="color: red">${this.keyword}</span>`)
    },
    // 执行搜索
    search() {
      this.keyword = this.keyword.trim() // 去除首尾空格
    }
  }
}
</script>

使用 Vue.js 的 v-html 指令高亮匹配关键字的示例代码:

<template>
  <div>
    <input v-model="keyword" placeholder="Search...">
    <ul>
      <li v-for="item in filteredList" :key="item.id">
        <span v-html="highlight(item.title)"></span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      list: [
        { id: 1, title: 'Apple' },
        { id: 2, title: 'Banana' },
        { id: 3, title: 'Cherry' },
        { id: 4, title: 'Durian' },
        { id: 5, title: 'Elderberry' },
      ],
    };
  },
  computed: {
    filteredList() {
      return this.list.filter(item => item.title.toLowerCase().includes(this.keyword.toLowerCase()));
    },
  },
  methods: {
    highlight(value) {
      if (!this.keyword) {
        return value;
      }
      const regex = new RegExp(`(${this.keyword})`, 'gi');
      return value.replace(regex, '<span class="highlight">$1</span>');
    },
  },
};
</script>

<style scoped>
.highlight {
  background-color: yellow;
}
</style>