vue 实现多选框
Vue 实现多选框的方法
在 Vue 中实现多选框可以通过多种方式完成,以下是几种常见的方法:
使用 v-model 绑定数组
Vue 的 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>
<p>Selected options: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'orange', label: 'Orange' },
],
selectedOptions: [],
};
},
};
</script>
动态生成多选框
如果需要动态生成多选框,可以结合 v-for 循环遍历选项数据。

<template>
<div>
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
/>
{{ item.name }}
</div>
<p>Selected items: {{ selectedItems }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
selectedItems: [],
};
},
};
</script>
使用计算属性处理选中状态
如果需要更复杂的逻辑,可以使用计算属性或方法来处理选中状态。
<template>
<div>
<label v-for="fruit in fruits" :key="fruit">
<input
type="checkbox"
:value="fruit"
@change="toggleSelection(fruit)"
:checked="isSelected(fruit)"
/>
{{ fruit }}
</label>
<p>Selected fruits: {{ selectedFruits }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Orange'],
selectedFruits: [],
};
},
methods: {
toggleSelection(fruit) {
const index = this.selectedFruits.indexOf(fruit);
if (index === -1) {
this.selectedFruits.push(fruit);
} else {
this.selectedFruits.splice(index, 1);
}
},
isSelected(fruit) {
return this.selectedFruits.includes(fruit);
},
},
};
</script>
使用第三方组件库
如果需要更丰富的功能,可以使用第三方组件库(如 Element UI、Vuetify 或 Ant Design Vue)提供的多选框组件。
<template>
<div>
<el-checkbox-group v-model="checkedCities">
<el-checkbox v-for="city in cities" :label="city" :key="city">
{{ city }}
</el-checkbox>
</el-checkbox-group>
<p>Selected cities: {{ checkedCities }}</p>
</div>
</template>
<script>
export default {
data() {
return {
cities: ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'],
checkedCities: [],
};
},
};
</script>
注意事项
- 确保每个多选框的
value唯一,避免冲突。 - 使用
v-model时,绑定的数组会自动更新,无需手动处理选中状态。 - 如果需要自定义逻辑,可以通过
@change事件手动处理选中状态。
以上方法可以根据实际需求选择适合的方式实现多选框功能。






