v-model with checkboxes helps you easily link checkbox inputs to your data. It keeps your data and checkboxes in sync without extra code.
v-model with checkboxes in Vue
<input type="checkbox" v-model="dataProperty" :value="optionValue" />
If v-model is bound to a boolean, the checkbox is checked when true and unchecked when false.
If v-model is bound to an array, the checkbox adds or removes its value from the array automatically.
isChecked is true.<input type="checkbox" v-model="isChecked" />
selectedFruits. Checking adds the fruit to the array.<input type="checkbox" v-model="selectedFruits" value="apple" /> <input type="checkbox" v-model="selectedFruits" value="banana" />
This Vue component shows three checkboxes for fruits. The selectedFruits array updates automatically as you check or uncheck boxes. The selected fruits are displayed below.
<template>
<div>
<h2>Select your favorite fruits:</h2>
<label>
<input type="checkbox" v-model="selectedFruits" value="Apple" /> Apple
</label>
<label>
<input type="checkbox" v-model="selectedFruits" value="Banana" /> Banana
</label>
<label>
<input type="checkbox" v-model="selectedFruits" value="Cherry" /> Cherry
</label>
<p>You selected: {{ selectedFruits.length ? selectedFruits.join(', ') : 'None' }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const selectedFruits = ref([])
</script>When using v-model with checkboxes and arrays, the checkbox's value attribute is important to identify what gets added or removed.
For a single checkbox bound to a boolean, no value attribute is needed.
Remember to initialize your data property properly: boolean for single checkbox, array for multiple checkboxes.
v-model with checkboxes links checkbox inputs to your data easily.
Use a boolean for single checkboxes, and an array for multiple checkboxes.
Checkboxes update your data automatically as users interact with them.