模糊搜索不区分大小写且高亮匹配文字

 <el-select
      ref="headerSearchSelect"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="请输入报表关键词"
      @change="change"
      popper-class="select-con"
      clearable
    >
      <!-- :transfer="true"
      :popper-append-to-body="false" -->
      <svg-icon class-name="search-icon" slot="prefix" icon-class="search" />

      <el-option
        v-for="option in options"
        :key="option.path + option.label"
        :value="option.value"
        :label="option.label"
      >
        <span v-html="option.name"></span>
      </el-option>
    </el-select>
import Fuse from 'fuse.js/dist/fuse.min.js';

querySearch(query) {
      this.keywords = query;
      if (query !== '') {
        let options = this.fuse.search(query);
        this.getResult(options); 
        this.options = this.setHightLight(options, query);
        let obj = [
          {
            path: '/dataAssets/dataMap',
            name: '查看全部搜索结果',
            label: '查看全部搜索结果'
          }
        ];
        obj[0].value = obj[0]; // 为了衔接上一个前端的后续逻辑,此处这样写是保持数据统一
        this.options = obj.concat(this.options);
      } else {
        this.options = [];
      }
    },


getResult(arr) {
      arr.forEach((element, index, arr) => {
        arr[index] = {
          label:
            this.menuTypeObj[element.item.menuType] +
            ':' +
            element.item.title.join(' > '),
          path: element.item.path ? element.item.path : '',
          value: element.item
        };
      });
    },

 //设置高亮的逻辑
    setHightLight(arr, keywords) {
      if (arr && arr.length > 0) {
        arr = arr.filter((item) => {
          let reg = new RegExp(keywords, 'gi');

          if (item.label.match(reg)) {
            //为了不影响原始name,我们这里给item重新设置一个parseName,模板中显示的是parseName

            item.name = item.label.replace(reg, function (txt) {
              return `<span style="color:#011128;padding:0">${txt.trim()}</span>`;
            });

            return item;
          }
        });
        return arr;
      } else {
        return [];
      }
    }
 initFuse(list) {
      this.fuse = new Fuse(list, {
        shouldSort: true,
        threshold: 0.4,
        location: 0,
        distance: 100,
        maxPatternLength: 32,
        minMatchCharLength: 1,
        keys: [
          {
            name: 'title',
            weight: 1
          }
          // {
          //   name: 'path',
          //   weight: 0.3
          // }
          // {
          //   name: 'menuType',
          //   weight: 0.1
          // }
        ]
      });
    },  
posted @ 2023-07-17 15:52  sinceForever  阅读(93)  评论(0编辑  收藏  举报