element ui--下拉根据拼音首字母过滤

很多场景下我们的下拉不仅仅要根据选项中的字过滤,还要根据拼音首字母过滤,现在我们来实现下。

要获取汉字拼音,可以用pinyin-pro库来实现

1.导入拼音库

复制代码
npm install pinyin-pro

下面的代码可以获取companyName的拼音,返回的是数组,不包含声调

javascript 复制代码
import { pinyin } from 'pinyin-pro';

pinyin(companyName, { toneType: 'none', type: 'array' })

2.调用接口,获取数据,然后遍历数据,设置拼音首字母

javascript 复制代码
    getCompanyList() {
      this.reportLoading=true
      listBasecompany({pageNum: 1,
        pageSize: 100,req:{isValid:1}}).then(response => {
        response.data.content.forEach(item=>{
          //组合拼音首字母
          item.firstPinyin = pinyin(item.companyName, { toneType: 'none', type: 'array' }).map(item=>{
            return item.substring(0, 1).toLowerCase()
          }).join('')
        })
        this.companyList = response.data.content;
        this.filterCompanyList = Object.assign(this.companyList);
      }).finally(()=>{
        this.reportLoading=false
      });
    },

这段代码的作用就是拿到汉字的拼音首字母,如天气返回的就是tq

我们要克隆一份filterCompanyList,option需要通过这个来生成

我们看下html代码怎么写

html 复制代码
          <el-form-item
            label="单位名称"
            prop="companyId"
            class="label-right-align"
          >
            <el-select
              v-model="checkForm.companyId"
              class="full-width-input"
              :filter-method="companyFilter"
              clearable
              filterable
              style="width: 110%"
              @clear="clearCompany"
            >
              <el-option
                v-for="(item, index) in filterCompanyList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>

我们来看下重点代码,需要开启filterable,然后重写filter-method方法,el-option的key要用id,不要用index,否则某些输入会导致select重渲染导致输入框里面的值丢失

companyFilter就比较简单了,把包含输入项,或者起始是拼音首字母的过滤出来,赋值给filterCompanyList

javascript 复制代码
    companyFilter(v) {
      this.filterCompanyList = this.companyList.filter((item) => {
        // 如果直接包含输入值直接返回true
        if (item.companyName.indexOf(v) !== -1 || item.firstPinyin.startsWith(v)) return true;
      });
    },

最后一点注意事项,如果你开启了clearable,要重写clear方法

javascript 复制代码
	clearCompany(){
      this.filterCompanyList=this.companyList
    },
相关推荐
β添砖java3 小时前
CSS3核心技术
前端·css·css3
空山新雨(大队长)3 小时前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
猫头虎-前端技术4 小时前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫4 小时前
探索 CSS 过渡:打造流畅网页交互体验
前端·css
元亓亓亓4 小时前
JavaWeb--day1--HTML&CSS
前端·css·html
β添砖java4 小时前
CSS的文本样式
前端·css
前端小趴菜054 小时前
css - 滤镜
前端·css
祈祷苍天赐我java之术4 小时前
理解 CSS 浮动技术
前端·css
索迪迈科技4 小时前
Flex布局——详解
前端·html·css3·html5