vue实现多选下拉
Vue 多选下拉实现方法
使用原生 HTML 和 Vue 指令
<template>
<select v-model="selectedOptions" multiple>
<option v-for="option in options" :value="option.value">
{{ option.text }}
</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{ value: '1', text: '选项1' },
{ value: '2', text: '选项2' },
{ value: '3', text: '选项3' }
]
}
}
}
</script>
使用 Element UI 组件库
<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: '1',
label: '选项1'
}, {
value: '2',
label: '选项2'
}, {
value: '3',
label: '选项3'
}]
}
}
}
</script>
使用 Vue Multiselect 插件
安装插件:
npm install vue-multiselect
使用示例:
<template>
<multiselect
v-model="selectedOptions"
:options="options"
:multiple="true"
:close-on-select="false"
placeholder="选择项目"
label="text"
track-by="value">
</multiselect>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
components: { Multiselect },
data() {
return {
selectedOptions: [],
options: [
{ value: '1', text: '选项1' },
{ value: '2', text: '选项2' },
{ value: '3', text: '选项3' }
]
}
}
}
</script>
自定义多选下拉组件
<template>
<div class="custom-multiselect">
<div class="selected-options" @click="toggleDropdown">
<span v-for="(option, index) in selectedOptions" :key="index">
{{ getOptionText(option) }}
<span @click.stop="removeOption(index)">×</span>
</span>
</div>
<div class="dropdown" v-show="isOpen">
<div
v-for="(option, index) in options"
:key="index"
@click="selectOption(option)"
:class="{ selected: isSelected(option) }">
{{ option.text }}
</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
},
selectOption(option) {
if (!this.isSelected(option)) {
this.selectedOptions.push(option.value)
} else {
this.selectedOptions = this.selectedOptions.filter(
val => val !== option.value
)
}
this.$emit('input', this.selectedOptions)
},
removeOption(index) {
this.selectedOptions.splice(index, 1)
this.$emit('input', this.selectedOptions)
},
isSelected(option) {
return this.selectedOptions.includes(option.value)
},
getOptionText(value) {
const option = this.options.find(opt => opt.value === value)
return option ? option.text : ''
}
}
}
</script>
注意事项
- 原生 HTML select 多选样式有限,可能需要额外 CSS 美化
- 组件库方案通常提供更丰富的功能和更好的用户体验
- 自定义组件需要考虑键盘交互、无障碍访问等细节
- 多选数据绑定使用数组类型 v-model
- 大数据量时需考虑性能优化,如虚拟滚动







