Vue2实现全选反选功能
注:代码未设置样式,只是一个简单的全选反选功能。
(废话不多说,上代码)
<template><div class="container"><table><tr v-for="(item, index) in demo"><td v-if="index === 0"><inputtype="checkbox"v-model="checked"@click="checkedAll()">全选</input></td><td v-if="index !== 0"><input type="checkbox" v-model="checkList" :value="item.id" /></td><td>{{item.name }}</td></tr></table></div></template>
//data里面定义的数据demo: [{id: 0,name: "姓名",},{id: "1",name: "小李",},{id: "2",name: "小张",},{id: "3",name: "小王",},],checked: false,checkList: [],
//逻辑代码methods: {//点击全选事件checkedAll() {var that = this;if (that.checked) {//实现反选that.checkList = [];} else {//实现全选that.checkList = [];that.demo.forEach(function (item, index) {if (index > 0) {that.checkList.push(item.id);}});}},},watch: {//深度 watchercheckList: {handler: function (val, oldVal) {if (val.length === this.demo.length - 1) {this.checked = true;} else {this.checked = false;}},deep: true,},},