vue实现checkbox
Vue 实现 Checkbox
在 Vue 中实现复选框(checkbox)可以通过 v-model 实现数据双向绑定,结合 v-for 动态渲染多个选项。以下是几种常见实现方式:
单个 Checkbox 绑定
通过 v-model 绑定布尔值,表示复选框的选中状态:
<template>
<div>
<input type="checkbox" id="checkbox" v-model="isChecked" />
<label for="checkbox">是否同意协议</label>
<p>当前状态:{{ isChecked ? '已选中' : '未选中' }}</p>
</div>
</template>
<script>
export default {
data() {
return {
isChecked: false
}
}
}
</script>
多个 Checkbox 绑定数组
通过 v-model 绑定数组,存储选中的值:
<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: 'apple', label: '苹果' },
{ value: 'banana', label: '香蕉' },
{ value: 'orange', label: '橙子' }
],
selectedOptions: []
}
}
}
</script>
自定义 Checkbox 组件
封装可复用的 Checkbox 组件,支持自定义样式和事件:
<!-- Checkbox.vue -->
<template>
<div class="custom-checkbox" @click="toggle">
<div :class="['checkbox-inner', { 'is-checked': isChecked }]"></div>
<span class="checkbox-label"><slot /></span>
</div>
</template>
<script>
export default {
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: Boolean
},
computed: {
isChecked() {
return this.checked
}
},
methods: {
toggle() {
this.$emit('change', !this.isChecked)
}
}
}
</script>
<style scoped>
.custom-checkbox {
display: flex;
align-items: center;
cursor: pointer;
}
.checkbox-inner {
width: 16px;
height: 16px;
border: 1px solid #dcdfe6;
margin-right: 8px;
}
.checkbox-inner.is-checked {
background-color: #409eff;
border-color: #409eff;
}
</style>
使用自定义组件:
<template>
<div>
<Checkbox v-model="checked">自定义复选框</Checkbox>
<p>状态:{{ checked }}</p>
</div>
</template>
<script>
import Checkbox from './Checkbox.vue'
export default {
components: { Checkbox },
data() {
return {
checked: false
}
}
}
</script>
与表单验证集成
结合 Vuelidate 或 Element UI 等库实现表单验证:

<template>
<div>
<input
type="checkbox"
v-model="form.agree"
@change="$v.form.agree.$touch()"
/>
<label>同意条款</label>
<p v-if="$v.form.agree.$error" class="error">必须同意条款</p>
</div>
</template>
<script>
import { required } from 'vuelidate/lib/validators'
export default {
data() {
return {
form: {
agree: false
}
}
},
validations: {
form: {
agree: { required }
}
}
}
</script>
以上方法覆盖了 Vue 中实现复选框的常见场景,可根据实际需求选择或组合使用。






