I think @Jeremy’s answer is cleaner way, but it require for checked property on each user object which is makes no sense if the data come from an API request.
Here is working and cleaner code for select/deselect all rows without having to add checked property on user object:
new Vue({
el: '#app',
data: {
users: [
{ "id": "1", "name": "Shad Jast", "email": "pfeffer.matt@yahoo.com" },
{ "id": "2", "name": "Duane Metz", "email": "mohammad.ferry@yahoo.com" },
{ "id": "3", "name": "Myah Kris", "email": "evolkman@hotmail.com" },
{ "id": "4", "name": "Dr. Kamron Wunsch", "email": "lenora95@leannon.com" }
],
selected: []
},
computed: {
selectAll: {
get: function () {
return this.users ? this.selected.length == this.users.length : false;
},
set: function (value) {
var selected = [];
if (value) {
this.users.forEach(function (user) {
selected.push(user.id);
});
}
this.selected = selected;
}
}
}
});
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<div id="app">
<h4>User</h4>
<div>
<table>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th align="left">Name</th>
</tr>
<tr v-for="user in users">
<td>
<input type="checkbox" v-model="selected" :value="user.id" number>
</td>
<td>{{ user.name }}</td>
</tr>
</table>
</div>
</div>
Please note that the number attribute on row’s checkbox is required, otherwise you have to push the user id selectAll method as a string, like selected.push(user.id.toString());