0
0
Vueframework~15 mins

v-model with checkboxes in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using v-model with Checkboxes in Vue
📖 Scenario: You are building a simple preferences form for a website where users can select their favorite fruits using checkboxes.
🎯 Goal: Create a Vue component that uses v-model to bind an array of selected fruits to multiple checkboxes. The component should update the array automatically when checkboxes are checked or unchecked.
📋 What You'll Learn
Create a Vue component with a reactive array called selectedFruits initialized as empty.
Add a list of fruit names as checkboxes in the template.
Use v-model on each checkbox to bind it to selectedFruits.
Display the currently selected fruits below the checkboxes.
💡 Why This Matters
🌍 Real World
Checkbox groups are common in forms where users select multiple options, such as preferences, filters, or interests.
💼 Career
Understanding how to bind multiple checkboxes to a reactive array with v-model is essential for building interactive forms in Vue applications.
Progress0 / 4 steps
1
Set up the initial data array
Create a Vue component with a reactive array called selectedFruits initialized as an empty array [] inside the setup() function using ref.
Vue
Need a hint?

Use import { ref } from 'vue' and then const selectedFruits = ref([]) inside <script setup>.

2
Add a list of fruit checkboxes
In the <template>, add three checkboxes with labels: Apple, Banana, and Cherry. Use input elements of type checkbox with value attributes set to the fruit names.
Vue
Need a hint?

Use three input elements with type="checkbox" and value set to each fruit name.

3
Bind checkboxes with v-model
Add v-model="selectedFruits" to each checkbox input to bind them to the reactive array selectedFruits.
Vue
Need a hint?

Add v-model="selectedFruits" to each checkbox input to link them to the reactive array.

4
Display selected fruits
Below the checkboxes, add a <div> that shows the text Selected fruits: followed by the joined list of fruits in selectedFruits using {{ selectedFruits.join(', ') }}.
Vue
Need a hint?

Use {{ selectedFruits.join(', ') }} inside a <div> to display the selected fruits separated by commas.