Element-UI下拉框select实现拼音搜索

688 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

需求:用户要求打出首字母就能搜索到中文内容,而不是必须输入汉字才能触发搜索。

需求分析:element自带搜索功能,支持汉字搜索,拼音的话需要引入第三方插件了。经过实验 pinyin-match完美实现。

解决过程:

首先安装插件 npm install pinyin-match --save

全局引用和局部引用皆可,这里我们使用了局部引用 import pinyin from "pinyin-match"

给select标签添加 filterable :filter-method="pinyingMatch"

添加自定义搜索方法,注意data中要添加一个otherList数组,一个copyotherList数组,为了保存所有数据,如果没有搜索到,就展示所有内容。

pinyingMatch(val) {
      var that = this
      const pinyingMatch = require("pinyin-match");
      if (val) {
        var result = [];
        //
        //注意otherList是内容数组,根据自己项目修改
        that.otherList.forEach((e) => {
        //注意,e.employeeName是遍历数组之后的键,按需修改
          var m = pinyingMatch.match(e.employeeName, val);
          // console.log(m);
          if (m) {
            result.push(e);
          }
        });
        //搜索到相应的数据就把符合条件的n个数据赋值brand
        that.otherList = result;
      } else {
        //没有搜索到数据,就还展示所有的brand
        //copyotherList也是内容数组,为了显示全部,需要添加进之前的内容
        that.otherList = that.copyotherList;
      }
    }

标签代码

      <el-form-item prop="driver">
        <el-select
          v-model="dataForm.driverName"
          placeholder="司机名"
          filterable
          :filter-method="pinyingMatch"
          clearable
          @clear="deleteName()"
        >
          <el-option
            v-for="item in otherList"
            :key="item.employeeName"
            :label="item.employeeName"
            :value="item.employeeName"
          ></el-option>
        </el-select>
      </el-form-item>

成功解决。

--------------------------------------更新---------------------------------------------------

发现了一些BUG:elementUI的下拉选择,每次点击×删除之后,v-model绑定的数据没有删除,所以要添加@clear方法,将data清空,同时把otherList还原。

    deleteName(){
      this.dataForm.driverName = ''
      this.otherList = this.copyotherList
    }

--------------------------------------更新---------------------------------------------------

又出现了Bug,每次输入拼音字母,输入框的字母都会消失,这是由于v-for遍历数组时加入了Index,每次Index变化就会导致这个情况,去掉即可。