vue2.0 實現全選和全不選


實現思路:

1、 v-model 一個收集所有input(除全選框外)數組checkModel ,vue會動態將其checked為true的input的value值存入數組checkModel里

2 、watch函數來監聽checkModel 屬性,當其長度==input元素時 全選按鈕選中 否則取消

3 、全選按鈕v-model checked 屬性來顯示當前選中狀態 click事件里 當checked為true時 全選 所有input按鈕被選中也就是checkModel的遍歷存入其value值

html代碼:

<div>
  <input type="checkbox" @click="checkAll" v-model="checked">
  <span>全選</span>
</div>
<ul>
  <li v-for="(item,index) in list" :key="index" style="margin-top:20px;">
    <input type="checkbox" v-model="checkModel" :value="item.id">
    <span>{{item.name}}--</span>
    <span>{{item.age}}--</span>
    <span>{{item.money}}元</span>
    <mt-button @click="remove(index)" type="primary">刪除</mt-button>
  </li>
</ul>

js代碼:

data(){
  return {
    list:[
      {id:1,name:"明明",age:23,money:100},
      {id:2,name:"紅紅",age:18,money:200},
      {id:3,name:"強強",age:29,money:300}
    ],
    checked:false, //是否全選
    checkModel:[] //雙向數據綁定的數組,我是用的id
  }
},
watch:{
  checkModel(){
    if(this.checkModel.length==this.list.length){
      this.checked=true;
    }else{
      this.checked=false;
    }
  }
},
methods:{  
  checkAll(){
    if(this.checked){
      this.checkModel=[];
    }else{
      this.list.forEach((item)=>{
      if(this.checkModel.indexOf(item.id)==-1){
        this.checkModel.push(item.id)
      }
      })
    }
  }
}

效果如圖:

Alt

注:刪除效果我用的是element-ui,有興趣的朋友可以研究下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM