0
0
Vueframework~5 mins

v-model with checkboxes in Vue

Choose your learning style9 modes available
Introduction

v-model with checkboxes helps you easily link checkbox inputs to your data. It keeps your data and checkboxes in sync without extra code.

When you want to select multiple options from a list using checkboxes.
When you need to update your data automatically as users check or uncheck boxes.
When building forms that require multiple selections, like choosing hobbies or skills.
When you want simple two-way binding between checkboxes and an array or boolean value.
When you want to reduce manual event handling for checkbox inputs.
Syntax
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.

Examples
Checkbox linked to a boolean. Checked if isChecked is true.
Vue
<input type="checkbox" v-model="isChecked" />
Checkboxes linked to an array selectedFruits. Checking adds the fruit to the array.
Vue
<input type="checkbox" v-model="selectedFruits" value="apple" />
<input type="checkbox" v-model="selectedFruits" value="banana" />
Sample Program

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.

Vue
<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>
OutputSuccess
Important Notes

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.

Summary

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.