遇到一个需求,一开始是通过下拉列表来设置值(支持过滤),后来要求也可以直接输入值。查了网上的解决方案,都不能完全满足。综合了一下,最终解决方案如下:
<template>
<el-select
v-model="value"
allow-create
default-first-option
filterable
:filter-method="onFilter"
@change="onChange()"
@blur="onBlur()"
placeholder="Select"
style="width: 240px"
>
<el-option
v-for="item in filterOpts"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const value = ref('')
const options = [
{
value: 'Option1',
label: 'Option1',
},
{
value: 'Option2',
label: 'Option2',
},
{
value: 'Option3',
label: 'Option3',
},
{
value: 'Option4',
label: 'Option4',
},
{
value: 'Option5',
label: 'Option5',
},
]
const filterOpts = ref(options)
// 暂存输入框内容
let input = ''
function onFilter(text) {
console.log(text)
input = text
filterOpts.value = options.filter(opt => !text || opt.label.indexOf(text)>-1)
}
// 重置输入内容
function onChange() {
input = ''
}
// 失去焦点时,如果输入框有内容,则以输入内容为准
function onBlur() {
if (input) {
value.value = input
}
console.log('blur', value.value)
}
</script>