vue实现select组件多选
实现多选 Select 组件
在 Vue 中实现多选 Select 组件可以通过原生 <select> 结合 multiple 属性或使用第三方 UI 库(如 Element UI、Ant Design Vue)。以下是两种常见实现方式:
原生 HTML 实现
使用原生 <select> 标签并添加 multiple 属性,通过 v-model 绑定数组类型数据:
<template>
<select v-model="selectedOptions" multiple>
<option v-for="option in options" :value="option.value">
{{ option.label }}
</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{ value: 'opt1', label: 'Option 1' },
{ value: 'opt2', label: 'Option 2' },
{ value: 'opt3', label: 'Option 3' }
]
}
}
}
</script>
使用 Element UI 实现
安装 Element UI 后直接使用 el-select 组件:
<template>
<el-select v-model="selectedOptions" multiple placeholder="请选择">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [{
value: 'opt1',
label: 'Option 1'
}, {
value: 'opt2',
label: 'Option 2'
}, {
value: 'opt3',
label: 'Option 3'
}]
}
}
}
</script>
自定义样式与功能
若需要完全自定义实现,可参考以下结构:
<template>
<div class="custom-multi-select">
<div
class="selected-options"
@click="toggleDropdown">
<span v-for="opt in selectedOptions">
{{ getLabel(opt) }}
</span>
</div>
<div v-show="isOpen" class="dropdown">
<div
v-for="option in options"
@click="toggleOption(option.value)"
:class="{ selected: isSelected(option.value) }">
{{ option.label }}
</div>
</div>
</div>
</template>
<script>
export default {
props: {
options: Array,
value: Array
},
data() {
return {
isOpen: false,
selectedOptions: this.value || []
}
},
methods: {
toggleDropdown() {
this.isOpen = !this.isOpen
},
toggleOption(value) {
const index = this.selectedOptions.indexOf(value)
index === -1
? this.selectedOptions.push(value)
: this.selectedOptions.splice(index, 1)
this.$emit('input', this.selectedOptions)
},
isSelected(value) {
return this.selectedOptions.includes(value)
},
getLabel(value) {
const option = this.options.find(opt => opt.value === value)
return option ? option.label : ''
}
}
}
</script>
注意事项
- 多选场景下
v-model必须绑定数组类型 - 原生实现需自行处理样式和交互体验
- 第三方库通常提供更完善的功能(如搜索、标签展示等)
- 移动端需考虑交互适配问题







