vue点击实现多选
实现多选的基本思路
在Vue中实现多选功能通常需要维护一个数组来存储选中的项,通过点击事件动态添加或移除元素。以下是两种常见场景的实现方法。
基于列表的多选实现
创建一个数组存储选中项的ID或对象,通过v-for渲染列表,利用v-model或点击事件切换选中状态。
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="toggleSelection(item)"
:class="{ 'selected': selectedItems.includes(item.id) }"
>
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '选项1' },
{ id: 2, name: '选项2' },
{ id: 3, name: '选项3' }
],
selectedItems: []
}
},
methods: {
toggleSelection(item) {
const index = this.selectedItems.indexOf(item.id);
if (index === -1) {
this.selectedItems.push(item.id);
} else {
this.selectedItems.splice(index, 1);
}
}
}
}
</script>
<style>
.selected {
background-color: #42b983;
color: white;
}
</style>
使用复选框组实现多选
通过v-model直接绑定到数组,适合表单提交场景。
<template>
<div>
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
:id="'checkbox-' + item.id"
:value="item.id"
v-model="selectedItems"
>
<label :for="'checkbox-' + item.id">{{ item.name }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '选项1' },
{ id: 2, name: '选项2' },
{ id: 3, name: '选项3' }
],
selectedItems: []
}
}
}
</script>
对象数组的完整选择处理
当需要存储整个对象而非ID时,可使用findIndex进行比较。
methods: {
toggleSelection(item) {
const index = this.selectedItems.findIndex(
selected => selected.id === item.id
);
if (index === -1) {
this.selectedItems.push(item);
} else {
this.selectedItems.splice(index, 1);
}
}
}
性能优化建议
对于大型列表,使用Set或对象哈希来提升查找效率。

data() {
return {
selectedSet: new Set()
}
},
methods: {
toggleSelection(id) {
if (this.selectedSet.has(id)) {
this.selectedSet.delete(id);
} else {
this.selectedSet.add(id);
}
}
}
注意事项
- 确保为循环项设置唯一的
:key - 复杂对象建议使用深拷贝避免引用问题
- 移动端可添加
@touchstart事件增强交互体验






