How to handle checkboxes in Vue
Handling checkboxes in Vue enables interactive forms with single or multiple selection capabilities using v-model directive for seamless two-way data binding. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented checkbox handling in thousands of Vue forms across enterprise applications for user preferences and data selection. From my expertise, the most effective approach is using v-model with arrays for multiple checkboxes and boolean values for single checkboxes. This method provides reactive checkbox states with automatic data synchronization and clean form handling.
Use v-model with arrays for multiple checkboxes and boolean values for single checkbox controls.
<template>
<div>
<!-- Single checkbox -->
<label>
<input type="checkbox" v-model="agreedToTerms">
I agree to terms
</label>
<!-- Multiple checkboxes -->
<div>
<label>
<input type="checkbox" value="javascript" v-model="selectedSkills">
JavaScript
</label>
<label>
<input type="checkbox" value="vue" v-model="selectedSkills">
Vue.js
</label>
<label>
<input type="checkbox" value="react" v-model="selectedSkills">
React
</label>
</div>
<p>Agreed: {{ agreedToTerms }}</p>
<p>Skills: {{ selectedSkills }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const agreedToTerms = ref(false)
const selectedSkills = ref([])
</script>
For single checkboxes, v-model binds to a boolean value that toggles true/false. For multiple checkboxes, v-model binds to an array where the value attribute determines what gets added or removed from the array when the checkbox is checked or unchecked.
Best Practice Note:
This is the same checkbox handling approach we use in CoreUI Vue components for form controls and user preference management.