I wonder if I use array as model for multiple-checkbox list, how can I check which items is checked and which are unchecked efficiently rather than compare one by one with that array?
<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" @change="handleTasks(task)">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>
new Vue({
data: {
tasks: [
{ title: 'Go to the store' },
{ title: 'Clean the house' },
{ title: 'Learn Vue.js' }
],
selectedTasks: []
},
})
If a checkbox is marked or checked, it indicates to true; this means that the user has selected the value. If a checkbox is unmarked or not checked, it indicated to false; this means that the user has not selected the value.
In order to check if a checkbox is checked or unchecked, we can used the isSelected() method over the checkbox element. The isSelected() method returns a boolean value of true if the checkbox is checked false otherwise.
prop('checked'); which will return true if checkbox is checked or not.
You could add a property to each task
(e.g., checked
) and bind that to each input's v-model
, making it trivial in code to check whether a task is checked/selected:
new Vue({
el: '#app',
data() {
return {
tasks: [
{ title: 'Go to the store', checked: false },
{ title: 'Clean the house', checked: false },
{ title: 'Learn Vue.js', checked: false }
]
};
},
methods: {
clearCheckedTasks() {
this.tasks = this.tasks.filter(x => !x.checked);
}
}
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" v-model="task.checked">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>
<button @click="clearCheckedTasks">Clear checked tasks</button>
<h3>tasks (live)</h3>
<pre>{{tasks}}</pre>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With