Vue.js checkbox 练习
<div id="app"> <input type="checkbox" v-model="sex" value="1" />足球 <input type="checkbox" v-model="sex" value="2" />篮球 <input type="checkbox" v-model="sex" value="3" />乒乓球 <br /> {{sex}} <br /> <button v-on:click="clickall(true)">全选</button> <button v-on:click="clickall(false)">取消全选</button> </div> <script type="text/javascript"> var vm = new Vue({ el: "#app", data: { sex:[] } , methods: { clickall: function (flag) { if (flag) { _this = this; this.sex = []; $.each($(":checkbox"), function (i, v) { _this.sex.push(v.value); }); } else { this.sex = []; } } } }); </script>
用自定义指令实现全选和取消全选 <div id="app"> <ul> <li v-for="item in list"> <input type="checkbox" v-sel="item.checked" /> {{item.name}} </li> </ul> <br /> {{list}} <br /> <button v-on:click="clickall(true)">全选</button> <button v-on:click="clickall(false)">取消全选</button> </div> <script type="text/javascript"> Vue.directive("sel", function (el, v) { if (v.value) { $(el).attr("checked", "checked"); } else { $(el).removeAttr("checked"); } }); var vm = new Vue({ el: "#app", data: { list: [{ name: "足球", checked: true }, { name: "篮球", checked: false }, { name: "乒乓球", checked: true }] }, mounted:function() { } , methods: { clickall: function (flag) { if (flag) { this.list.forEach(function (v, i) { v.checked = true; }); } else { this.list.forEach(function (v, i) { v.checked = false; }); } } } }); </script>