vue实现复选择框
Vue 实现复选框
在 Vue 中实现复选框可以通过 v-model 指令绑定到数据属性,支持单选、多选或动态渲染复选框组。
基础实现
通过 v-model 绑定布尔值控制单个复选框的选中状态:

<template>
<div>
<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{ checked ? '已选中' : '未选中' }}</label>
</div>
</template>
<script>
export default {
data() {
return {
checked: false
}
}
}
</script>
多选绑定数组
多个复选框可绑定到同一个数组,选中的值会自动添加到数组中:
<template>
<div>
<input type="checkbox" id="apple" value="apple" v-model="fruits">
<label for="apple">Apple</label>
<input type="checkbox" id="banana" value="banana" v-model="fruits">
<label for="banana">Banana</label>
<p>选中的水果:{{ fruits }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fruits: []
}
}
}
</script>
动态渲染复选框组
通过 v-for 动态生成复选框列表:

<template>
<div>
<div v-for="option in options" :key="option.value">
<input
type="checkbox"
:id="option.value"
:value="option.value"
v-model="selectedOptions"
>
<label :for="option.value">{{ option.label }}</label>
</div>
<p>已选择:{{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'vue', label: 'Vue.js' },
{ value: 'react', label: 'React' },
{ value: 'angular', label: 'Angular' }
],
selectedOptions: []
}
}
}
</script>
自定义样式与组件封装
使用 <label> 包裹 <input> 并隐藏原生样式,通过 CSS 自定义外观:
<template>
<label class="custom-checkbox">
<input type="checkbox" v-model="checked" hidden>
<span class="checkmark"></span>
{{ label }}
</label>
</template>
<script>
export default {
props: ['label', 'value'],
computed: {
checked: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
}
}
</script>
<style>
.custom-checkbox {
display: flex;
align-items: center;
cursor: pointer;
}
.checkmark {
width: 20px;
height: 20px;
border: 2px solid #ccc;
margin-right: 8px;
position: relative;
}
input:checked + .checkmark::after {
content: "✓";
position: absolute;
top: -2px;
left: 3px;
}
</style>
与表单验证集成
结合 Vuelidate 等库实现验证:
<template>
<div>
<input
type="checkbox"
v-model="acceptTerms"
@blur="$v.acceptTerms.$touch()"
>
<label>同意条款</label>
<p v-if="$v.acceptTerms.$error" class="error">必须接受条款</p>
</div>
</template>
<script>
import { required } from 'vuelidate/lib/validators'
export default {
data() {
return {
acceptTerms: false
}
},
validations: {
acceptTerms: { required }
}
}
</script>






