el-select使用filter-method实现自定义过滤

最近有个任务要用el-select来自定义过滤,发现有很多细节,网上搜的很多不够严谨,情况考虑不全,此处给出完整解决方案

实现DEMO

  • filter-method input里输入时才会触发,和input上的change事件一样,它只会传一个参数:检索的文字。要结合各种情况,自己过滤出optionsFilter给option赋值

  • 容易遗漏的情况:当输入一段和下面选项不匹配的文字时,此时过滤的结果列表是空,这时点击空白处,检索文字会自动清空,过滤结果保持是空,会影响下一次搜索,所以需要配合@focus来重置过滤结果

html 复制代码
<template>
  <div>
    <el-select v-model="seledMan"
               clearable
               filterable
               size="small"
               :filter-method="filterMan"
               placeholder="请选择"
               @change="searchFirstList"
               @clear="filterMan"
               @focus="filterMan()">
      <el-option v-for="item in optionsFilter"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>
<script>
export default {
  data() {
    return {
      optionsOrigin: [
        { value: 'zhangsan', label: '张三' },
        { value: 'lisi', label: '李四' },
        { value: 'wangwu', label: '王五' },
        { value: 'zhaoliu', label: '赵六' },
      ],
      optionsFilter: [],

      seledMan: '',
    }
  },
  methods: {
    filterMan(query) {
      console.log('触发过滤')
      if (!query) {
        this.optionsFilter = this.optionsOrigin
        return
      }
      const queryStr = query.toLowerCase()
      const filterList = this.optionsOrigin.filter((option) => {
        const nameZh = option.label,
          namePY = option.value.toLowerCase()
        return nameZh.includes(queryStr) || namePY.includes(queryStr)
      })
      this.optionsFilter = filterList
    },

    searchFirstList() {
      //选择人之后,重置页面为第一页,触发检索
      console.log('selDone', this.seledMan)
    },
  },
  created() {
    // 也可以是接口获取optionsOrigin后,同时赋给optionsFilter
    this.optionsFilter = [...this.optionsOrigin]
  },
  mounted() {},
  computed: {},
}
</script>
<style lang="scss" scoped>
</style>
相关推荐
mayaairi1 小时前
Vue2 组件通讯(三):全局事件总线、PubSub、插槽与组件实例属性
前端·javascript·vue.js
kyriewen2 小时前
面试官问我:AI 都能写代码了,前端凭什么还值 25K
前端·javascript·人工智能
风骏时光牛马3 小时前
AI源码分析:拆解模型底层实现逻辑
前端
IT_陈寒3 小时前
React子组件莫名其妙重渲染?你可能漏了这个Hook
前端·人工智能·后端
乘风gg3 小时前
DeepSeek V4.1 Flash 来了,明天中午 Flash 降价 60%
前端·ai编程·claude
默_笙3 小时前
❗ 给金鱼装记忆(上):从白板到笔记本,AI 的短期记忆生存指南
前端·javascript
酷酷的逗逗乐3 小时前
前端转 Agent 开发 · 第五节:Memory 会话记忆
前端·程序员
掘金挖土4 小时前
前端手摸手跑路之 AI 应用开发(二)
前端·后端
mayaairi4 小时前
Vue2 组件通讯(四):v-model、scoped样式、mixins与plugins
前端·javascript·vue.js
梦曦i4 小时前
@meng-xi/uni-router 未来展望:夯实基础、深化体验、探索前沿
前端·uni-app