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

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

📢 ant-design

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

👉① 配置可搜索 showSearch

image.png

<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学号进行搜索,用户是无需知道学号的也是不可能背学号的。这里应该是展示什么,我们搜索某个字来显示这个人的记录,这里也就是学生的名字。如下:

Kapture 2023-08-12 at 10.57.33.gif

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

👉② 搜索时对应的属性 optionFilterProp

<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)类型。

image.png

📢 element-plus

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

👉① 配置可搜索 filterable

image.png

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

👉② 实现搜索逻辑 filter-method

自定义筛选条件

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

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;
  });
};

Kapture 2023-08-12 at 14.23.57.gif

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

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

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

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务