vue实现多选搜索
Vue 多选搜索实现方法
使用 Element UI 的 Select 组件
Element UI 提供了带有搜索功能的多选组件,适合快速实现需求。
安装 Element UI:
npm install element-ui
代码示例:

<template>
<el-select
v-model="selectedItems"
multiple
filterable
placeholder="请搜索并选择"
@change="handleChange">
<el-option
v-for="item in filteredOptions"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
selectedItems: [],
options: [
{ value: '1', label: '选项1' },
{ value: '2', label: '选项2' }
],
searchQuery: ''
}
},
computed: {
filteredOptions() {
return this.options.filter(option =>
option.label.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
methods: {
handleChange(value) {
console.log(value)
}
}
}
</script>
自定义实现多选搜索
对于需要完全自定义的场景,可以结合 input 和 checkbox 实现。
<template>
<div class="multi-select">
<input
v-model="searchQuery"
placeholder="搜索..."
@input="filterOptions">
<div class="options">
<div
v-for="option in filteredOptions"
:key="option.value"
class="option">
<input
type="checkbox"
:id="option.value"
:value="option.value"
v-model="selectedItems">
<label :for="option.value">{{ option.label }}</label>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
selectedItems: [],
options: [
{ value: '1', label: '选项1' },
{ value: '2', label: '选项2' }
],
filteredOptions: []
}
},
created() {
this.filteredOptions = [...this.options]
},
methods: {
filterOptions() {
this.filteredOptions = this.options.filter(option =>
option.label.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
<style>
.multi-select {
border: 1px solid #dcdfe6;
padding: 10px;
border-radius: 4px;
}
.options {
max-height: 200px;
overflow-y: auto;
}
.option {
padding: 5px 0;
}
</style>
使用 Vue Multiselect 插件
vue-multiselect 是专门为 Vue 设计的强大多选组件。

安装:
npm install vue-multiselect
使用示例:
<template>
<multiselect
v-model="selected"
:options="options"
:multiple="true"
:searchable="true"
:close-on-select="false"
placeholder="搜索并选择"
label="label"
track-by="value">
</multiselect>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
components: { Multiselect },
data() {
return {
selected: [],
options: [
{ label: '选项1', value: 1 },
{ label: '选项2', value: 2 }
]
}
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
实现远程搜索
当需要从服务器获取选项时,可以使用防抖技术优化性能。
<script>
export default {
methods: {
fetchOptions: _.debounce(function(query) {
axios.get('/api/options', { params: { q: query } })
.then(response => {
this.options = response.data
})
}, 500)
},
watch: {
searchQuery(newVal) {
this.fetchOptions(newVal)
}
}
}
</script>
注意事项
- 大数据量情况下考虑虚拟滚动优化性能
- 移动端需要特别注意触摸交互体验
- 选中的项目需要有明确的视觉反馈
- 考虑添加全选/清除全部等快捷操作
以上方法可根据实际项目需求选择使用,Element UI 方案适合快速开发,自定义方案灵活性最高,vue-multiselect 则提供了丰富的开箱即用功能。






