vue实现全选与反选的例子

两种实现方法:

1)第一种方法

<template>
<div>
<input type="checkbox" :checked="options.length === checkboxs.length" @click="onAll">
<span>全选</span>
<div v-for="option in options ">
<input type="checkbox"
:checked="option.checked"
@click="option.checked = !option.checked"
v-model="checkboxs"
:value="option" />
<span>{{option.studentName}}</span>
</div>
</div>
</template>
<script type="text/babel">
export default{
data(){
return{
checkboxs:[],
options:[
{studentName:'张三',id:1},
{studentName:'李四',id:2},
{studentName:'王四',id:3},
],
}
},
methods:{
//全选
onAll() {
if (this.options.length === this.checkboxs.length) {
this.checkboxs = [];
} else {
this.checkboxs = this.options.concat()
}
},
},
}
</script>

 

2)第二种实现方法(这种方法的全选与反选按钮不好用,存在浏览器兼容性问题,建议还是使用第一种方式)
<template>
<div id="app">

<div>
<label>
<input type="checkbox" v-model="checkAll" @click="onAll">全选
</label>
</div>
<ul>
<li v-for="item in list">
<label>
<input type="checkbox" v-model="checkboxs" :value="item.id">
{{ item.name }}
</label>
</li>
</ul>
<!-- <p>checkboxs: {{ checkboxs }}</p> -->

</div>
</template>
<script>
export default {
data(){
return{
list: [
{ id: 1, name: '测试1', age: 21 },
{ id: 2, name: '测试2', age: 18 },
{ id: 3, name: '测试3', age: 17 }
],
checkboxs: [],
checkAll: false
}
},
methods:{
onAll: function() {
if (this.checkAll) {
this.checkboxs = []
this.list.forEach((item) => this.checkboxs.push(item.id) )
} else {
this.checkboxs = [];
}
},
},
watch:{
checkboxs: function() {
this.checkAll = this.checkboxs.length === 3 ? true : false;
}
},
}
</script>

 

本人菜鸟一枚,欢迎大家指教

 

posted @ 2017-09-11 15:28  MonicaSmile  阅读(316)  评论(0)    收藏  举报