v-model with checkboxes. What will be the value of selectedFruits after the user checks 'Apple' and 'Banana'?<template>
<div>
<label><input type="checkbox" value="Apple" v-model="selectedFruits"> Apple</label>
<label><input type="checkbox" value="Banana" v-model="selectedFruits"> Banana</label>
<label><input type="checkbox" value="Cherry" v-model="selectedFruits"> Cherry</label>
</div>
</template>
<script setup>
import { ref } from 'vue'
const selectedFruits = ref([])
</script>When multiple checkboxes share the same v-model bound to an array, Vue automatically adds or removes the checkbox's value to/from the array as the user checks or unchecks them. Checking 'Apple' and 'Banana' adds both strings to the array.
v-model. Which code snippet correctly achieves this?Using v-model on a single checkbox binds the checked state to a boolean variable. Adding a value attribute changes the behavior to array binding or string values, which is not desired here.
selectedColors array?<template>
<div>
<label><input type="checkbox" :value="color" v-model="selectedColors"> {{ color }}</label>
</div>
</template>
<script setup>
import { ref } from 'vue'
const colors = ['Red', 'Green', 'Blue']
const selectedColors = ref([])
</script>The code only renders one checkbox with a variable color that is undefined in the template. To bind multiple checkboxes, you need to loop over colors to create one checkbox per color.
selectedOptions after the user checks 'Option1', then 'Option3', then unchecks 'Option1'?<template> <label><input type="checkbox" value="Option1" v-model="selectedOptions"> Option1</label> <label><input type="checkbox" value="Option2" v-model="selectedOptions"> Option2</label> <label><input type="checkbox" value="Option3" v-model="selectedOptions"> Option3</label> </template> <script setup> import { ref } from 'vue' const selectedOptions = ref([]) </script>
Initially, checking 'Option1' adds it to the array. Checking 'Option3' adds it too. Unchecking 'Option1' removes it, leaving only 'Option3' in the array.
v-model, what happens if one checkbox lacks a value attribute?<template> <label><input type="checkbox" v-model="selected" value="A"> A</label> <label><input type="checkbox" v-model="selected"> B</label> <!-- Missing value --> </template> <script setup> import { ref } from 'vue' const selected = ref([]) </script>
In HTML, a checkbox without a value attribute defaults to the string 'on'. Vue uses this default as the value added to the array when checked.