当前位置:主页 > 网页前端 > vue >

vue 全选与反选的实现方法(无Bug 新手看过来)

时间:2021-04-16 08:23:17 | 栏目:vue | 点击:

我就废话不多说,直接上代码吧!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<div style="padding-left: 20px">
<ul style="margin-bottom: 20px"> 
<li v-for="(item, index) in proData">
<input type="checkbox" :value="index" v-model="selectArr">{{item.name}}
</li>
</ul>
<label> 
<input type="checkbox" @click="selectAll" :checked="checked"/>全选 
</label> 
</div> 
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script type="text/javascript">
var vm = new Vue({
el : "#app",
data : {
proData: [
   {
 "name": "张三"
}, {
 "name": "李四"
}, {
 "name": "王五"
}, {
 "name": "赵六"
}
],
   selectArr: [],
   checked : false
},
watch : {
 selectArr(curVal){
 if(curVal.length == this.proData.length){
 this.checked = true
 }else{
 this.checked = false
 }
 }
 },
 methods: {
  selectAll(event){
   if (!event.currentTarget.checked) {
    this.selectArr = [];
   } else { //实现全选
    this.selectArr = [];
    this.proData.forEach((item, i) =>{
     this.selectArr.push(i);
    });
   }
  }
 }
})
</script>
</html>

如果有bug,请告知!

您可能感兴趣的文章:

相关文章