checkbox 全选
<template> <div class="hello"> <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> <!-- 下面是热身测试 --> <hr><br><br> <input type="checkbox" v-model="flag"><br> <input type="checkbox" v-model="arr" value="1"> <input type="checkbox" v-model="arr" value="2"> <input type="checkbox" v-model="arr" value="3"> </div> </template> <script> export default { name: "HelloWorld", data() { return { 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: [],
// ** 下面是热身的 ** flag: true, arr: ["1"] }; }, methods: {}, 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>
热身部分解释:
1、v-model为true或者false能控制checkbox勾选与否,
v-model="flag"
2、数组集合里的元素是否包含当前checkbox的value也能控制勾选与否,
v-model="arr" value="3" 意思是如果arr
正文解释:
return this.users ? this.selected.length == this.users.length : false;
1、users集合是否为空?为空直接不全选
2、已选择的单选框的元素个数是否等于Users集合的元素个数
3、等于的话返回true,意思是已然全选;不等于返回false,不全选