vue 多选实现思路
多选框基础实现
使用v-model绑定数组类型数据,配合checkbox的value属性实现多选功能。当勾选时,对应value会被添加到数组中;取消勾选时从数组中移除。
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedValues"
:value="option.value"
>
{{ option.label }}
</label>
<p>已选择: {{ selectedValues }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' },
{ value: 'C', label: '选项C' }
],
selectedValues: []
}
}
}
</script>
自定义多选组件封装
封装可复用的多选框组件,支持动态选项和自定义样式。通过props接收选项列表,通过$emit触发选择变化事件。

<template>
<div class="multi-select">
<div
v-for="item in options"
:key="item.value"
class="select-item"
:class="{ 'active': isSelected(item.value) }"
@click="toggleSelect(item.value)"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
value: {
type: Array,
default: () => []
}
},
methods: {
isSelected(val) {
return this.value.includes(val)
},
toggleSelect(val) {
const newValue = [...this.value]
const index = newValue.indexOf(val)
index === -1
? newValue.push(val)
: newValue.splice(index, 1)
this.$emit('input', newValue)
}
}
}
</script>
<style scoped>
.select-item {
padding: 8px 12px;
border: 1px solid #ddd;
cursor: pointer;
margin-right: 5px;
display: inline-block;
}
.select-item.active {
background-color: #409eff;
color: white;
}
</style>
全选/反选功能实现
添加全选控制逻辑,通过计算属性判断是否全选,并提供全选/取消全选的方法。

computed: {
isAllSelected: {
get() {
return this.selectedValues.length === this.options.length
},
set(val) {
this.selectedValues = val
? this.options.map(item => item.value)
: []
}
}
}
多选表格实现
在表格中实现多选行功能,结合el-table等UI组件库使用时需要注意行数据的唯一标识。
<el-table
ref="multipleTable"
:data="tableData"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<script>
export default {
methods: {
handleSelectionChange(val) {
this.selectedRows = val
},
toggleSelection(rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row)
})
}
}
}
</script>
多选数据验证
对多选结果进行验证,确保至少选择N项或符合特定条件。
validateSelection() {
if (this.selectedValues.length < 2) {
this.$message.error('请至少选择两项')
return false
}
return true
}






