In this article, we will look at how to work with the input element to create checkboxes in Vue.
We will begin by creating a new application using Vue CLI.
❯ vue create checkbox-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd checkbox-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
v-model
We can make use of the v-model
directive to create a two-way binding for the <input>
tag with the type checkbox in Vue.
Single Checkbox
Let’s first look at an example of how to handle a single checkbox using v-model
directive.
<input type="checkbox" value="subscribe" name="subscribe" v-model="subscribe" />
Here, we have a single subscribe checkbox that can store a boolean value of true
if the checkbox is checkout or false
if not checked. Let’s create a data property subscribe
to hold this value. By default, we can set the value of subscribe
to null
or false
.
data() {
return {
subscribe: false,
};
}
We can add the above code in the App.vue
file to see the single checkbox working in action:
// App.vue
<template>
<input
type="checkbox"
id="subscribe"
value="subscribe"
name="subscribe"
v-model="subscribe"
/>
<label for="apple">Subscribe</label><br />
<p>Subscribed: {{ subscribe }}</p>
</template>
<script>
export default {
name: "App",
data() {
return {
subscribe: null,
};
},
};
</script>
Multiple Checkboxes
Let’s look at how to define and store multiple checkbox values using v-model
directive.
<input type="checkbox" value="apple" id="apple" v-model="fruits" />
<label for="apple">Apple</label><br />
<input type="checkbox" value="orange" id="orange" v-model="fruits" />
<label for="orange">Orange</label><br />
<input type="checkbox" value="grapes" id="grapes" v-model="fruits" />
<label for="grapes">Grapes</label><br />
Here, we have multiple checkboxes and each checkbox refers to the same v-model
value of fruits
so that we can group them as one. The multiple selections of checkboxes can be stored in an array. Let’s define a data property fruits
and assign it a default value of an empty array.
data() {
return {
fruits: [],
};
}
Let’s make these changes in the App.vue
file to see checkboxes in action.
// App.vue
<template>
<input
type="checkbox"
id="apple"
value="apple"
name="apple"
v-model="fruits"
/>
<label for="apple">Apple</label><br />
<input
type="checkbox"
id="orange"
value="orange"
name="orange"
v-model="fruits"
/>
<label for="orange">Orange</label><br />
<input
type="checkbox"
id="grapes"
value="grapes"
name="grapes"
v-model="fruits"
/>
<label for="grapes">Grapes</label><br />
<p>Selected checkbox: {{ fruits }}</p>
</template>
<script>
export default {
name: "App",
data() {
return {
fruits: [],
};
},
};
</script>
As you can see from the above screenshot, multiple selections are stored as an array of checkbox values.