vue中自定义 多选带搜索框的下拉列表
时间: 2024-11-24 09:41:19 浏览: 103
在 Vue 中,创建一个多选带搜索框的下拉列表,通常会结合使用 `v-model` 与数组绑定,`v-select` 组件(比如 Element UI 提供的 `el-option`),以及自定义的搜索事件。以下是一个简单的例子:
首先,安装并引入必要的库:
```bash
npm install element-ui@latest
```
然后,在 Vue 模板中定义下拉列表:
```html
<template>
<el-form-item label="多选带搜索框下拉列表">
<el-select v-model="selectedOptions" multiple placeholder="请选择">
<el-option
v-for="item in filteredOptions"
:key="item.id"
:label="item.label"
:value="item.value"
@input="handleOptionChange"
:disabled="item.disabled"
></el-option>
</el-select>
<input type="text" v-model="searchText" placeholder="搜索...">
</el-form-item>
</template>
```
在 JavaScript 中,定义相关的数据和方法:
```javascript
<script>
import { computed, defineComponent } from 'vue';
import { ElOption } from 'element-plus';
export default defineComponent({
components: {
ElOption,
},
data() {
return {
selectedOptions: [], // 存储选择的选项
searchText: '', // 搜索文本
options: [
{ id: 1, value: 'Option 1', label: 'Option 1 Label' },
... // 更多选项
],
filteredOptions: computed(() => {
const filtered = this.options.filter(item =>
item.label.toLowerCase().includes(this.searchText.toLowerCase())
);
return this.selectedOptions.length > 0 ? filtered.filter(option => !this.selectedOptions.includes(option)) : filtered;
}),
};
},
methods: {
handleOptionChange(value) {
if (!Array.isArray(value)) {
value = [value];
}
this.selectedOptions = [...new Set([...this.selectedOptions, ...value])];
},
},
});
</script>
```
在这个例子中,当搜索文本改变时,`filteredOptions` 会动态过滤出匹配的结果;同时,用户选择的选项会存储在 `selectedOptions` 数组中。`handleOptionChange` 方法用于处理 `v-model` 的值变化。
阅读全文
相关推荐


















