Checkboxes

A checkbox answers a yes-or-no question, such as whether the order is to go. With v-model on a ref that holds true or false, the checkbox is checked while the ref is true, and checking it makes the ref true:

<script setup>
import { ref } from "vue";

const toGo = ref(false);
</script>

<template>
    <label>
        <input type="checkbox" v-model="toGo">
        To go
    </label>
    <p>{{ toGo ? "In a paper cup" : "In a mug" }}</p>
</template>

Several checkboxes can also fill one array. Give each its own value, and all of them the same v-model, on a ref that holds an array:

<script setup>
import { ref } from "vue";

const extras = ref([]);
</script>

<template>
    <label>
        <input type="checkbox" value="milk" v-model="extras">
        Milk
    </label>
    <label>
        <input type="checkbox" value="sugar" v-model="extras">
        Sugar
    </label>
    <p>{{ extras.join(", ") }}</p>
</template>

Check Sugar, then Milk, and extras is ["sugar", "milk"]: the values of the checked boxes, in the order they were checked. The paragraph shows sugar, milk. Uncheck Sugar, and it's gone from the array. It's an ordinary array, so all you know about arrays works on it: extras.length, extras.includes("milk"), extras.join(", ").

Typical mistake:

  • A ref that doesn't start as an array, such as ref(""). Vue then treats the checkboxes as yes-or-no ones: checking one makes the ref true, and all of them are checked at once.

Instructions

  1. Connect the checkbox #to-go with toGo. In the summary, add a paragraph that says To go while it's checked, and For here while it isn't.

  2. Give the three checkboxes of the extras the values milk, sugar and cinnamon, and connect them with extras. The summary then lists the checked ones: Extras: milk, cinnamon.

  3. When no extra is checked, the summary says Extras: none.