vue 模糊搜索框 实现 搜索的内容与下拉框相同文字高亮显示

使用正则表达式:

html
<template>
  <div>
    <input type="text" v-model="searchText" @input="filterItems">
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        <span v-html="highlightText(item.text)"></span>
      </li>
    </ul>
  </div>
</template>
 <script>
export default {
  data() {
    return {
      searchText: '',
      items: [
        { id: 1, text: '苹果' },
        { id: 2, text: '香蕉' },
        { id: 3, text: '橙子' },
        { id: 4, text: '苹果派' },
        { id: 5, text: '橙汁' },
      ],
    };
  },
  computed: {
    filteredItems() {
      if (this.searchText === '') {
        return this.items;
      }
      return this.items.filter(item => item.text.includes(this.searchText));
    },
  },
  methods: {
    highlightText(value) {
      const regex = new RegExp(this.searchText, 'gi');
      return value.replace(regex, '<span class="highlight">$&</span>');
    },
  },
};
</script>
 <style>
.highlight {
  color: blue;
}
</style>

在上面的示例中,我们使用了一个方法 highlightText 来处理文字高亮。在模板中,我们使用 v-html 指令来渲染带有HTML标签的内容,从而将匹配的部分用 <span> 标签包裹起来,并添加 .highlight 类来设置文字颜色为蓝色。 无论使用过滤器还是正则表达式,你都可以根据实际需求来选择适合的方法来实现模糊搜索框中搜索内容与下拉框重复的文字变成蓝色。

在我的项目中模糊筛选用的时vue中<el-autocomplete>的方法,我使用了他的插槽

<el-form-item label="授权店铺"> 
          <el-autocomplete
            v-model.trim="shopName"
            :clearable="true"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入授权店铺"
            @select="handleSelect"
          >
            <template slot-scope="{ item }"> //item为数组元素,Object
              <div>{{ item.address }}</div> //下拉列表显示的值已更改为address值
            </template>
          </el-autocomplete>

在这个做了一点改变,将

 <div>{{ item.address }}</div> //改变为

<div v-html="highlightText(item.text)"></div>

这样就可以改变下拉框中每一行的代码样式,让他高亮显示。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值