vue实现多选div
实现多选 Div 的基本思路
在 Vue 中实现多选 Div 功能,通常需要结合 v-model 或自定义事件管理选中状态,通过 CSS 类动态切换样式。核心逻辑包括数据绑定、状态管理和样式交互。
基础实现示例
模板部分
使用 v-for 渲染多个 Div,通过 v-model 或点击事件切换选中状态:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
class="selectable-div"
:class="{ 'selected': selectedItems.includes(item.id) }"
@click="toggleSelection(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: [] // 存储选中项的 ID
};
},
methods: {
toggleSelection(id) {
const index = this.selectedItems.indexOf(id);
if (index === -1) {
this.selectedItems.push(id); // 选中
} else {
this.selectedItems.splice(index, 1); // 取消选中
}
}
}
};
</script>
样式部分
通过 CSS 高亮选中状态:
<style>
.selectable-div {
padding: 10px;
margin: 5px;
border: 1px solid #ddd;
cursor: pointer;
}
.selected {
background-color: #42b983;
color: white;
}
</style>
进阶功能扩展
支持 Ctrl/Shift 多选
监听键盘事件实现类似文件管理器的多选逻辑:
methods: {
handleClick(event, id) {
if (event.ctrlKey || event.metaKey) {
this.toggleSelection(id); // 追加选中
} else {
this.selectedItems = [id]; // 单选
}
}
}
使用计算属性过滤数据
动态获取已选中的数据项:
computed: {
selectedData() {
return this.items.filter(item =>
this.selectedItems.includes(item.id)
);
}
}
封装为可复用组件
将逻辑抽离为独立组件,通过 props 和 emits 实现父子通信:
子组件 (SelectableDivGroup.vue)
<template>
<div>
<div
v-for="item in items"
@click="$emit('select', item.id)"
:class="{ selected: selected.includes(item.id) }"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
props: {
items: Array,
selected: Array
}
};
</script>
父组件调用
<SelectableDivGroup
:items="dataList"
:selected="selectedIds"
@select="handleSelect"
/>
注意事项
- 若需要服务端保存选中状态,需通过 API 提交
selectedItems。 - 移动端需考虑触摸交互,可增加长按多选逻辑。
- 大数据量时建议使用虚拟滚动优化性能(如
vue-virtual-scroller)。







