vue点击实现多选
Vue 实现多选功能的方法
在 Vue 中实现多选功能可以通过多种方式完成,以下是几种常见的方法:
使用 v-model 绑定数组
通过 v-model 绑定一个数组,当复选框被选中时,其 value 会被添加到数组中。

<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.value"
/>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
],
selectedOptions: []
};
}
};
</script>
自定义多选逻辑
如果需要更复杂的逻辑,可以通过自定义方法实现多选功能。
<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: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 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: #f0f0f0;
}
</style>
使用第三方组件库
许多 Vue 组件库(如 Element UI、Vuetify)提供了现成的多选组件,可以直接使用。

以 Element UI 为例:
<template>
<el-checkbox-group v-model="checkedCities">
<el-checkbox
v-for="city in cities"
:label="city"
:key="city"
>
{{ city }}
</el-checkbox>
</el-checkbox-group>
</template>
<script>
export default {
data() {
return {
cities: ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'],
checkedCities: []
};
}
};
</script>
键盘辅助多选
如果需要支持类似桌面应用的多选行为(如按住 Shift 或 Ctrl 键多选),可以监听键盘事件。
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="handleClick($event, item)"
:class="{ 'selected': selectedItems.includes(item.id) }"
>
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selectedItems: [],
lastSelectedIndex: null
};
},
methods: {
handleClick(event, item) {
if (event.shiftKey && this.lastSelectedIndex !== null) {
// Shift 多选逻辑
const currentIndex = this.items.findIndex(i => i.id === item.id);
const start = Math.min(this.lastSelectedIndex, currentIndex);
const end = Math.max(this.lastSelectedIndex, currentIndex);
this.selectedItems = this.items.slice(start, end + 1).map(i => i.id);
} else if (event.ctrlKey || event.metaKey) {
// Ctrl/Cmd 多选逻辑
const index = this.selectedItems.indexOf(item.id);
if (index === -1) {
this.selectedItems.push(item.id);
} else {
this.selectedItems.splice(index, 1);
}
this.lastSelectedIndex = this.items.findIndex(i => i.id === item.id);
} else {
// 普通单选
this.selectedItems = [item.id];
this.lastSelectedIndex = this.items.findIndex(i => i.id === item.id);
}
}
}
};
</script>
以上方法可以根据实际需求选择或组合使用,实现灵活的多选功能。






