vue实现复选框逻辑
Vue 复选框基础实现
使用 v-model 绑定复选框状态到 Vue 的数据属性。这是最简单的双向绑定方式:
<template>
<input type="checkbox" v-model="isChecked">
<span>{{ isChecked ? '已选中' : '未选中' }}</span>
</template>
<script>
export default {
data() {
return {
isChecked: false
}
}
}
</script>
复选框组实现
处理多个复选框时,通常绑定到数组:

<template>
<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>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'apple', label: '苹果' },
{ value: 'banana', label: '香蕉' },
{ value: 'orange', label: '橙子' }
],
selectedOptions: []
}
}
}
</script>
自定义复选框组件
创建可复用的复选框组件:
<!-- Checkbox.vue -->
<template>
<label class="checkbox-container">
<input
type="checkbox"
:checked="modelValue"
@change="$emit('update:modelValue', $event.target.checked)"
>
<span class="checkmark"></span>
{{ label }}
</label>
</template>
<script>
export default {
props: {
modelValue: Boolean,
label: String
},
emits: ['update:modelValue']
}
</script>
<style>
.checkbox-container {
display: block;
position: relative;
padding-left: 35px;
cursor: pointer;
user-select: none;
}
</style>
全选功能实现
实现全选/取消全选逻辑:

<template>
<input type="checkbox" v-model="selectAll"> 全选
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
>
{{ item.name }}
</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>
与后端交互
处理表单提交时的复选框数据:
<template>
<form @submit.prevent="submitForm">
<input type="checkbox" v-model="formData.agree"> 同意条款
<button type="submit">提交</button>
</form>
</template>
<script>
export default {
data() {
return {
formData: {
agree: false
}
}
},
methods: {
submitForm() {
if (!this.formData.agree) {
alert('请先同意条款')
return
}
// 发送数据到API
console.log('提交数据:', this.formData)
}
}
}
</script>
性能优化建议
对于大量复选框的情况,考虑使用虚拟滚动或分页显示。避免在模板中使用复杂表达式,将逻辑移到计算属性中。使用 :key 帮助 Vue 高效更新 DOM。
注意事项
Vue 2 和 Vue 3 在自定义组件 v-model 实现上有差异。Vue 3 使用 modelValue 作为默认 prop,而 Vue 2 使用 value。处理复选框组时,确保绑定的数组在 data 中初始化,避免响应性问题。





