Antd/Antdv Select组件实现可输入且单选
实现思路:
1.options 共两个部分组成,一个部分为 请求option,即请求后端获取的列表;另一个部分为动态option,即不再 请求option列表中。由switchRef控制呈现那个option列表,默认展示请求列表;
2.用户输入时,判断输入的值是否为空字符串,
不为空字符串,则与请求option列表判断,如有包含关系,则switchRef设置为false(重复操作复位使用);不包含则switchRef设置为true;
为空字符串,则switchRef设置为false,用于展示请求option列表
实现代码:以Antdv select组件进而提供案例,antd也一样,都是相同用法,只是语法的区别
<template>
<Select
v-model:value="currentValue"
showSearch
:options="options"
@search="handleSearch"
@focus="handleFocus"
@select="handleSelect"
style="width:200px"
/>
</template>
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { Select, SelectOption } from 'ant-design-vue';
export default defineComponent({
name: 'CustomSelect',
components:{
Select,
SelectOption,
},
setup(props,content) {
const currentValue = ref(undefined)
//切换option列表状态 false:请求option列表 true: 动态option列表
const switchRef = ref(false)
//动态option列表
const dynamicOptions = ref([])
//请求option列表
const requestOptions = ref([])
const options = computed(() => {
if(switchRef.value){
return [...dynamicOptions.value]
}else{
return [...requestOptions.value]
}
})
//模拟请求后端接口返回options列表
const handleFocus = () => {
requestOptions.value = [
{
label:'张三',
value: '1'
},
{
label:'李四',
value: '2'
},
{
label:'王五',
value: '3'
}
]
//用于重新弹出下拉列表时 展示请求option列表
switchRef.value = false
}
const handleSearch = (value) => {
let arr = [...requestOptions.value]
if(value){
let panArr = arr.filter(item => item.label.includes(value))
if(panArr.length <= 0){
switchRef.value = true
dynamicOptions.value = [{
label:value,
value
}]
}else{
switchRef.value = false
}
}else{
switchRef.value = false
dynamicOptions.value = []
}
}
const handleSelect = (value) => {
currentValue.value = value
}
return {
currentValue,
options,
handleFocus,
handleSearch,
handleSelect,
}
}
});
</script>