前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue 复选框 checkbox 全选与取消全选

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

作者头像
sunonzj
发布2022-06-21 13:07:54
2.5K0
发布2022-06-21 13:07:54
举报
文章被收录于专栏:zjblogzjblog

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

代码语言:javascript
复制
<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>
代码语言:javascript
复制
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
`1IBX8E~%[LG5[~XT}]9H9S.png
1A0{C~[3J_US5J4}`}4U9[0.png
1A0{C~[3J_US5J4}`}4U9[0.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档