vuejs get value of checkbox group
To get the value of a checkbox group in Vue.js, you can follow these steps:
- Create a data property in your Vue instance to store the selected checkbox values. For example, you can define a property called "selectedOptions" and initialize it as an empty array:
data() {
return {
selectedOptions: []
}
}
- In your template, use the
v-model
directive to bind the checkbox inputs to the "selectedOptions" property. Make sure to use the same array for thev-model
and:value
attributes:
<template>
<div>
<input type="checkbox" value="option1" v-model="selectedOptions">
<input type="checkbox" value="option2" v-model="selectedOptions">
<input type="checkbox" value="option3" v-model="selectedOptions">
</div>
</template>
- To access the selected values, you can simply use the "selectedOptions" array in your Vue component's methods or computed properties. For example, you can log the selected values to the console:
methods: {
logSelectedOptions() {
console.log(this.selectedOptions);
}
}
Alternatively, you can use a computed property to return the selected values:
computed: {
selectedValues() {
return this.selectedOptions.join(', ');
}
}
In this example, the join()
method is used to concatenate the selected options into a comma-separated string.
By following these steps, you can get the value of a checkbox group in Vue.js.