vue实现复选择框
实现多选框的基本方法
在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>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'apple', label: '苹果' },
{ value: 'banana', label: '香蕉' },
{ value: 'orange', label: '橙子' }
],
selectedOptions: []
}
}
}
</script>
使用组件库实现
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: ['上海', '北京', '广州', '深圳'],
checkedCities: []
}
}
}
</script>
自定义样式多选框
可以通过隐藏原生input元素,使用label和span来自定义多选框样式:

<template>
<div class="custom-checkbox">
<label
v-for="item in items"
:key="item.id"
class="checkbox-label"
>
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
class="checkbox-input"
>
<span class="checkbox-custom"></span>
{{ item.name }}
</label>
</div>
</template>
<style>
.checkbox-input {
position: absolute;
opacity: 0;
}
.checkbox-custom {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #ccc;
margin-right: 10px;
position: relative;
}
.checkbox-input:checked + .checkbox-custom {
background-color: #409EFF;
border-color: #409EFF;
}
.checkbox-input:checked + .checkbox-custom::after {
content: "✓";
color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
全选/反选功能
实现全选和反选功能需要添加一个计算属性:
<template>
<div>
<label>
<input
type="checkbox"
v-model="selectAll"
> 全选
</label>
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="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: []
}
},
computed: {
selectAll: {
get() {
return this.selectedItems.length === this.items.length
},
set(value) {
this.selectedItems = value
? this.items.map(item => item.id)
: []
}
}
}
}
</script>
与表单验证集成
在使用Element UI时,可以结合表单验证规则:
<template>
<el-form :model="form" :rules="rules" ref="form">
<el-form-item label="选择城市" prop="cities">
<el-checkbox-group v-model="form.cities">
<el-checkbox
v-for="city in cityOptions"
:label="city"
:key="city"
>{{city}}</el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
cities: []
},
cityOptions: ['北京', '上海', '广州', '深圳'],
rules: {
cities: [
{ type: 'array', required: true, message: '请至少选择一个城市', trigger: 'change' }
]
}
}
}
}
</script>






