antd select解决设置可搜索不生效问题

本文主要讲如何解决antd或者element-plus中select搜索框设置show-search搜索时却搜不到或者只能根据id搜的问题。

📢 ant-design

如标题所示,用的是antdv框架,出现当设置select框为showSearch(配置是否可搜索时),却搜索不到或者只能根据id搜索到的这个问题。

👉① 配置可搜索 showSearch

xml 复制代码
<script setup lang="ts">
import { ref } from "vue";

const value = ref<string | undefined>(undefined);

const classArray = ref<[]>([
  { studentNumber: 101, name: "张三" },
  { studentNumber: 102, name: "李四" },
  { studentNumber: 103, name: "王五" },
]);

const handleChange = (value: string) => {
  console.log(`选中 ${value}`);
};
</script>

<style lang="scss" scoped>
.ant-select {
  width: 200px;
}
</style>

可是即使上面这个例子我们设置了show-search,可以搜索了,但是搜索只能根据studentNumber学号进行搜索,用户是无需知道学号的也是不可能背学号的。这里应该是展示什么,我们搜索某个字来显示这个人的记录,这里也就是学生的名字。如下:

解决办法就是加个optionFilterProp搜索时过滤对应的option属性。

👉② 搜索时对应的属性 optionFilterProp

ini 复制代码
<template>
  // a-select
  <a-select
    v-model:value="value"
    placeholder="搜索学生"
    show-search
    optionFilterProp="label"
    @change="handleChange"
  >
    <a-select-option v-for="item in classArray" :key="item.studentNumber" :value="item.studentNumber" :label="item.name">
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>

在<a-select>添加optionFilterProp="label",以及在<a-select-option>添加:label="item.name"。

antd的搜索功能默认是按照选项的value值来搜索的,而不是选项的内容。所以通过optionFilterProp指定按照哪个属性来进行搜索。

👉③ 其他办法 filterOption

还有一个办法就是根据filterOption来进行筛选。

filterOption 可以是布尔类型boolean,也可以是function(inputValue, option)类型。

📢 element-plus

element中的select, 只要添加filterable属性即可开启搜索。默认情况下,会找出所有label属性包含输入值的选项,如果希望使用匹配其他的搜索逻辑,可以通过传入filter-method去实现。

👉① 配置可搜索 filterable

element-plus中的filterable定义了开启一个搜索功能。

👉② 实现搜索逻辑 filter-method

自定义筛选条件

filter-method是一个函数,它会在输入值发生变化时进行调用,参数是当前输入的值,这里我们就可以写自己的逻辑代码。

ini 复制代码
const classArrayCopy = ref(classArray.value);
const filterMethod = (input) => {
  if (!input) {
    classArray.value = classArrayCopy.value;
    return;
  }

  classArray.value = classArray.value.filter((item) => {
    return item.name.indexOf(input) >= 0;
  });
};

注: ref() 函数是深拷贝。通过ref(classArray.value)深拷贝定义的classArray数组,便于清空时重置回原来的列表。

当然这里也可以用change方法来替代filter-method,原理就是根据输入的值改变select选项列表。

☎️ 希望对大家有所帮助,如有错误,望不吝赐教,欢迎评论区留言互相学习。

相关推荐
WJ.Polar18 分钟前
JavaScript入门
前端·javascript
夏与冰2 小时前
Vue2项目中数据字典的使用封装
前端·javascript·vue.js·elementui
map_vis_3d3 小时前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
kyriewen3 小时前
我把 7 个 UI 库的下拉框用键盘敲了一遍,3 家出了岔子
前端·javascript·程序员
陈随易3 小时前
MoonBit 2026 深圳线下交流分享
前端·后端·程序员
玖米GEO运营王总监3 小时前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
鼓掌MVP3 小时前
华为云码道实战:用 CodeArts Agent + 智能化搜索工具 API 调用自主开发「非遗文旅宣传卡生成器」
前端·人工智能·ai·html·ai编程·ai智能体·ai自动化
不要试图纠正别人4 小时前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
tryCbest4 小时前
Vue系列——第 24 篇:VueUse——组合式工具集的百宝箱
前端·vue.js
GuWenyue4 小时前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js