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, addtrue-value="yes"andfalse-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 andgenresis['fiction', 'history']. - Radios, one shared ref. The ref holds the
valueof whichever radio is selected. Because all three shareformat, only one can be chosen. Settingref('paper')pre-selects Paper. - Select, one ref. The ref holds the chosen option's
value. The disabled empty option acts as a prompt whileshelfis''. Add themultipleattribute 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.