回到顶部

×
原图

Vue 复选框 checkbox 全选与取消全选

按照jQuery的思想来做的话,要选中全选checkbox和所有的checkbox项,分别注册选中事件,判断选中状态来给相关的checkbox设置对应的状态,这就涉及到很多的dom操作。
下面就看一下vue数据驱动dom的思想来实现这一功能。

<table class="table table-bordered">
    <tr>
      <td><input type="checkbox" id="checkbox" v-model="checked" @change="changeAllChecked()"></td>
      <td>{{$t('account.name')}}</td>
      <td>{{$t('account.model')}}</td>
      <td>{{$t('account.onTime')}}</td>
      <td>{{$t('account.prepared')}}</td>
      <td>{{$t('account.Ip')}}</td>
      <td>{{$t('account.status')}}</td>
   </tr>
   <tr v-for="item in collectionList">
      <td><input type="checkbox" :id="item.name" :value="item.name" v-model="checkedNames"></td>
      <td>{{item.name}}</td>
      <td>{{item.model}}</td>
      <td>{{item.time}}</td>
      <td>{{item.yn}}</td>
      <td>{{item.ip}}</td>
      <td>{{item.status}}</td>
    </tr>
</table>
new Vue({
	el: '#app',
	data: {
        collectionList:[{name:'Collection1',model:'zy-asdsa21311231',status:'上线',yn:'y',time:'2019-6-30',ip:'192.168.8.78'},
                  {name:'Collection2',model:'zy-asdsa21311231',status:'失联',yn:'y',time:'2019-6-30',ip:'192.168.8.78'},
                  {name:'Collection3',model:'zy-asdsa21311231',status:'上线',yn:'n',time:'2019-6-30',ip:'192.168.8.78'},
                  {name:'Collection4',model:'zy-asdsa21311231',status:'上线',yn:'y',time:'2019-6-30',ip:'192.168.8.78'},
                  {name:'Collection5',model:'zy-asdsa21311231',status:'失联',yn:'n',time:'2019-6-30',ip:'192.168.8.78'}
          ],
      checkedNames: [],
      checked:false,
	},
	methods: {
		changeAllChecked: function() {
			if (this.checked) {
            var collectionList = this.collectionList
                for(let key in collectionList) {
                  console.log(collectionList[key]);
                  this.checkedNames.push(collectionList[key].name);
                }
			} else {
			    this.checkedNames = []
			}
		}
	},
	watch: {
	    "checkedNames": function() {
                      console.log(this.checkedNames+"---"+this.collectionList+"----"+this.checked);
			if (this.checkedNames.length == this.collectionList.length) {
				this.checked = true
			} else {
				this.checked = false
			}
		}
	}
})

效果:

`1IBX8E~%[LG5[~XT}]9H9S.png


1A0{C~[3J_US5J4}`}4U9[0.png

#去评论一下

留言评论