vue实现多选效果
Vue实现多选效果的方法
使用v-model绑定数组
通过v-model绑定一个数组类型的变量,配合checkbox的value属性实现多选。选中时值会自动添加到数组,取消选中时从数组移除。
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedItems"
:value="option.value"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'orange', label: 'Orange' }
],
selectedItems: []
}
}
}
</script>
使用第三方组件库
Element UI或Ant Design Vue等库提供现成的多选组件,例如el-checkbox-group:
<template>
<el-checkbox-group v-model="checkedList">
<el-checkbox
v-for="item in options"
:key="item.value"
:label="item.value"
>
{{ item.label }}
</el-checkbox>
</el-checkbox-group>
</template>
自定义多选逻辑
通过事件手动管理选中状态,适合需要高度定制的场景:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="toggleSelect(item.id)"
:class="{ 'active': selectedIds.includes(item.id) }"
>
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedIds: []
}
},
methods: {
toggleSelect(id) {
const index = this.selectedIds.indexOf(id)
index === -1
? this.selectedIds.push(id)
: this.selectedIds.splice(index, 1)
}
}
}
</script>
表格多选
配合表格组件实现行选择功能,常用el-table的selection功能:
<el-table
ref="multipleTable"
:data="tableData"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<!-- 其他列 -->
</el-table>
<script>
export default {
methods: {
handleSelectionChange(val) {
this.multipleSelection = val
}
}
}
</script>
注意事项
- 对象类型作为
value时需使用Vue.set确保响应式更新 - 大量数据时考虑性能优化,如虚拟滚动
- 移动端需注意触摸反馈和用户体验
- 可结合
computed属性实现全选/反选逻辑







