vue实现多选
Vue 实现多选的方法
使用 v-model 和复选框
在 Vue 中,可以通过 v-model 绑定一个数组来实现多选功能。当用户勾选多个复选框时,选中的值会自动添加到数组中。

<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.value"
/>
{{ option.label }}
</label>
<p>选中的选项: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
selectedOptions: []
};
}
};
</script>
使用第三方组件库(如 Element UI)
如果需要更丰富的多选功能,可以使用第三方 UI 库提供的多选组件。例如,Element UI 提供了 el-checkbox-group 和 el-checkbox 组件。

<template>
<div>
<el-checkbox-group v-model="selectedOptions">
<el-checkbox
v-for="option in options"
:key="option.value"
:label="option.value"
>
{{ option.label }}
</el-checkbox>
</el-checkbox-group>
<p>选中的选项: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
selectedOptions: []
};
}
};
</script>
自定义多选逻辑
如果需要更灵活的控制,可以手动实现多选逻辑,通过监听事件和操作数据。
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="toggleOption(option.value)"
:class="{ 'selected': selectedOptions.includes(option.value) }"
>
{{ option.label }}
</div>
<p>选中的选项: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
selectedOptions: []
};
},
methods: {
toggleOption(value) {
const index = this.selectedOptions.indexOf(value);
if (index === -1) {
this.selectedOptions.push(value);
} else {
this.selectedOptions.splice(index, 1);
}
}
}
};
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
多选下拉菜单
如果需要多选下拉菜单,可以使用 el-select 组件(Element UI)并设置 multiple 属性。
<template>
<div>
<el-select v-model="selectedOptions" multiple placeholder="请选择">
<el-option
v-for="option in options"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
<p>选中的选项: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
selectedOptions: []
};
}
};
</script>
以上方法可以根据具体需求选择使用,从简单的复选框到复杂的多选下拉菜单均可实现。






