Sometimes, we want to add a checkbox array in Vue.js.
In this article, we’ll look at how to add a checkbox array in Vue.js.
How to add a checkbox array in Vue.js?
To add a checkbox array in Vue.js, we can for the v-for
directive.
For instance, we write
<template>
<div id="app">
<div>
<label>Email</label>
<input type="text" v-model="user.email" />
</div>
<div v-for="role in roles" :key="role.id">
<label>{{ role.name }}</label>
<input type="checkbox" v-model="user.roles" :value="role" />
</div>
<p>User's selected roels</p>
{{ user.roles }}
</div>
</template>
<script>
//...
export default {
//...
data() {
return {
user: {
email: "[email protected]",
roles: [{ id: 1, name: "Client" }],
},
roles: [
{
id: 1,
name: "Client",
},
{
id: 2,
name: "Admin",
},
{
id: 3,
name: "Guest",
},
],
};
},
//...
};
</script>
to define the roles
reactive property.
We render the roles
array into checkboxes with the v-for
directive.
The key
prop is set to a unique value so Vue can distinguish between the items.
And we add an input with the type
attribute set to checkbox
inside to render checkboxes.
The value
prop is set to the value of each checkbox.
We set v-model
to user.roles
to bind the checked values to the user.roles
reactive property.
So user.roles
would have the value
prop value of each checkbox.
Conclusion
To add a checkbox array in Vue.js, we can for the v-for
directive.