Vue Element UI el-select 组件:输入查询及添加新选项
可以使用 el-select 组件的 'filterable' 属性来实现输入查询的功能。当用户输入内容时,可以通过设置一个过滤函数来实现查询相关的逻辑。当用户输入的内容不存在时,可以通过设置一个选项的插入函数来添加这个值。
以下是一个示例代码:
<template>
<el-select
v-model="selectedValue"
:filterable="true"
:remote-method="fetchOptions"
:remote="true"
@popper-show="resetOptions"
>
<el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value"></el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
selectedValue: '',
options: []
};
},
methods: {
fetchOptions(query) {
// 模拟异步请求数据
setTimeout(() => {
const filteredOptions = this.getFilteredOptions(query);
this.options = filteredOptions;
}, 200);
},
resetOptions() {
// 重置选项列表
this.options = [];
},
getFilteredOptions(query) {
// 根据查询内容筛选选项
const filteredOptions = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
].filter(option => {
return option.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
// 判断查询内容是否已存在于选项列表中
const isExist = filteredOptions.some(option => {
return option.value === query;
});
// 如果查询内容不存在于选项列表中,则添加这个值
if (query && !isExist) {
filteredOptions.push({ value: query, label: query });
}
return filteredOptions;
}
}
};
</script>
在上述示例代码中,通过设置 'filterable' 属性为 true,可以启用输入查询功能。通过设置 'remote-method' 属性为一个异步请求函数,可以执行异步获取选项的逻辑。在 fetchOptions 函数中,通过调用 getFilteredOptions 函数获取筛选后的选项,并将其赋值给 options 数组。在 getFilteredOptions 函数中,根据查询内容 query 筛选选项,并判断查询内容是否已存在于选项列表中,如果不存在则添加这个值。
原文地址: https://www.cveoy.top/t/topic/qqix 著作权归作者所有。请勿转载和采集!