el-checkbox实现全选与单选
实现目的:实现全选与多选,点击确定的时候获取每个值的id传给后台
1、HTML
1 <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> 2 <el-checkbox v-for="(city,i) in cities" :label="city.uuid" :key="i" v-model="city.relation" 3 @change="handleCheckedCitiesChange">{{city.customerName}}</el-checkbox> 5 6 <span slot="footer" class="dialog-footer"> 7 <el-button type="primary" :disabled="disabled" @click="classifyConfirm">确定</el-button> 8 <el-button type="primary" @click="calceConfirn">取消</el-button> 9 </span>
2、data
1 data: function () { 2 return { 3 checkAll: false, 4 cities: [], //数据源
5 }
6 }
3、js
1 handleCheckAllChange(val) { 2 if (this.checkAll) { 3 this.cities.forEach(item => { 4 item.relation = true //只改变数据的状态 5 }) 6 } else { 7 this.cities.forEach(item => { 8 item.relation = false 9 }) 10 } 11 }, 12 handleCheckedCitiesChange() { 13 console.log(this.checkedCities); 14 if (this.checkedCities.length == this.cities.length) { 15 this.checkAll = true 16 } else { 17 this.checkAll = false 18 } 19 },
1 //确认 2 classifyConfirm() { 3 var checkedAll = []; 4 this.cities.forEach(item => { 5 if(item.relation == true){ 6 checkedAll.push(item.uuid) //确认的时候取状态为true的值,并把要用的字段取出来 7 } 8 }) 9 // var checkedAll = [...new Set(this.checkedCities)] //数组去重 10 var that = this; 11 var data = { 12 "customerUuid":that.customerUuid, 13 "projectCustomerUuid":checkedAll.join(\',\') 14 }; 15 console.log(checkedAll) 16 this.classLoading = true; 17 $.ajax({ 18 url: Domain + \'/xxxxx\', 19 dataType: "json", 20 method: "POST", 21 // contentType: "application/json; charset=utf-8", 22 data:data, 23 success: function (ret) { 24 if (ret.retStatus == "1") { 25 that.$message({ 26 type: \'success\', 27 message: \'保存成功!\' 28 }); 29 that.classLoading = false;32 } 33 } 34 }) 35 },
最开始在改变状态的时候就想着取id了,导致后面一系列的问题,后面经过大佬的提醒,在最开始的时候不要取值,只改变状态就行,最后提交的时候遍历数组,然后把每一项里面为true的取出来就可以了,很简单就解决了
或者html 这样写也可以:
<el-checkbox :indeterminate=”roleIsIndeterminate” v-model=”roleCheckAll” @change=”handleRoleAllChange” :disabled=”isAllChecked || onlyAllDisabled”>全选</el-checkbox>
<el-checkbox-group v-model=”checkedRoles” @change=”handleCheckedRolesChange”>
<el-checkbox v-for=”role in roleList” :label=”role.id” :key=”role.id” :disabled=”role.disabled”>{{role.name}}</el-checkbox>
</el-checkbox-group>