美文网首页
el-select实现同时支持label和value搜索

el-select实现同时支持label和value搜索

作者: zkzhengmeng | 来源:发表于2024-01-02 14:55 被阅读0次

1.在el-select里开启filterable搜索功能 添加:filter-method="selectFilter" 通过自定义搜索

<el-select filterable class="search-input" :filter-method="selectFilter" v-model="selectNav" placeholder="请输入功能名称">
  <el-option
    v-for="item in filterArr "
    :key="item.value"
    :label="item.label"
    :value="item.value">
  </el-option>
</el-select>

2.在methods里增加方法selectFilter

定义了两个初始变量:
//filterArr : 当前下拉框的数组,即过滤后的数据
//temporary: 临时存放下拉菜单的数组即原始数据 ;
selectFilter(val){
  // 判断是否为空
  if( val ){
    // 同时筛选Lable与value的值
    this.filterArr = this.temporary.filter((item) => {
      if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase()) || !!~item.value.indexOf(val) || !!~item.value.toUpperCase().indexOf(val.toUpperCase()) ) {
        return true
      }
    })
  }else{
    // 赋值还原
    this.filterArr = this.temporary;
  }
},

3.注意事项

//当页面加载时,首先向filterArr 里获取下拉菜单的所有列表即原数据
//然后将 this.temporary= this.filterArr 用于存储下拉菜单的所有列表
接着当激活搜索的时候,会直接向selectFilter()里传入输入的参数 val
//接着判断当前输入的数值是否为空,如果不为空,则直接进入搜索,如果为空的话,
//this.filterArr = this.temporary; 将之前临时存放的数组再还原给filterArr 

相关文章