Skip to the workspace
Pebellslearn by building
Forms Handling  ›  Lesson

Checkboxes, Radios and Selects

v-model 14 minv-model adapts to each input type: a checkbox gives a boolean or an array, a radio gives its value, a select gives the chosen option's value.

vue / Checkboxes, Radios and Selects

Explore each scene at your own pace.

01 · The rule

The rule

Checkboxes, Radios and Selects

The Add Book form grows: a "Finished already" tick box, genre tick boxes, a choice of format, and a dropdown for the shelf it goes on. All of them use v-model, but each writes a different kind of value. Get the ref's starting type right and the rest follows.

The rule

The input's type and the ref's type together decide what v-model writes.

<script setup>
import { ref } from 'vue'

const finished = ref(false)        // one checkbox → boolean
const genres = ref([])             // many checkboxes → array
const format = ref('paper')        // radios → one value
const shelf = ref('')              // select → one value
</script>

<template>
  <label><input type="checkbox" v-model="finished" /> Finished already</label>

  <label><input type="checkbox" value="fiction" v-model="genres" /> Fiction</label>
  <label><input type="checkbox" value="science" v-model="genres" /> Science</label>
  <label><input type="checkbox" value="history" v-model="genres" /> History</label>

  <label><input type="radio" value="paper" v-model="format" /> Paper</label>
  <label><input type="radio" value="ebook" v-model="format" /> Ebook</label>
  <label><input type="radio" value="audio" v-model="format" /> Audio</label>

  <select v-model="shelf">
    <option disabled value="">Choose a shelf</option>
    <option value="now">Reading now</option>
    <option value="later">Read later</option>
  </select>
</template>

Type by type:

  • One checkbox, boolean ref. Ticked → true, unticked → false. If you want other values, add true-value="yes" and false-value="no".
  • Several checkboxes, one array ref. Each has its own value. Ticking pushes that value into the array; unticking removes it. Tick Fiction then History and genres is ['fiction', 'history'].
  • Radios, one shared ref. The ref holds the value of whichever radio is selected. Because all three share format, only one can be chosen. Setting ref('paper') pre-selects Paper.
  • Select, one ref. The ref holds the chosen option's value. The disabled empty option acts as a prompt while shelf is ''. Add the multiple attribute and bind an array to allow several choices.

Values do not have to be strings: :value="3" or :value="{ id: 3 }" binds real numbers or objects.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.