ElementUI Checkbox 多选框
一、概述
因项目需求,需要做一个多选设置。
先来看一下官方的demo
test.vue
<template> <div> <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选el-checkbox> <div style="margin: 15px 0;">div> <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange"> <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}el-checkbox> el-checkbox-group> div> template> <script> const cityOptions = ['上海', '北京', '广州', '深圳']; export default { data() { return { checkAll: false, checkedCities: ['上海', '北京'], cities: cityOptions, isIndeterminate: true }; }, methods: { handleCheckAllChange(val) { this.checkedCities = val ? cityOptions : []; this.isIndeterminate = false; }, handleCheckedCitiesChange(value) { let checkedCount = value.length; this.checkAll = checkedCount === this.cities.length; this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length; } } }; script>
效果如下:
indeterminate 属性用以表示 checkbox 的不确定状态,一般用于实现全选的效果。
当indeterminate为true时,会出现减号,表示不是全选。为false,会出现对勾,表示全选。
全选的标签用的是el-checkbox,v-model绑定的值是布尔值。
el-checkbox-group标签中,v-model绑定的值是数组,数组里面就是绑定的label的值。
二、项目演示
注意:在官方的demo中,使用的基础数据是:['上海', '北京', '广州', '深圳']
发现没有,它的数据机构很简单,在实际项目中,其实数据会比它复杂一点,比如:
[ { id:1, name:'上海', checkAll:false, isIndeterminate:false, checkedCities:[], children:[ { parentId:1, id:2, name:'松江区', }, { parentId:1, id:3, name:'杨浦区区', }, ] }, { id:10, name:'武汉', checkAll:false, isIndeterminate:false, checkedCities:[], children:[ { parentId:10, id:11, name:'汉阳区', }, { parentId:10, id:12, name:'武昌区', }, ] } ]
test.vue
"area-list" style="overflow:hidden" v-for="(item,index) in cities" :label="item.id" :key="item.id">"item.isIndeterminate" v-model="item.checkAll" @change="handleCheckAllChange($event,item)">{{item.name}} "item.checkedCities" class="a-row" @change="handleCheckedCitiesChange($event,item)"> for="(item2,index2) in item.children" :label="item2.id" :key="item2.id"> {{item2.name}}当前选择的是:{{option}}
效果如下:
注意:最左边的是一级菜单,后面的都是二级菜单。当二级菜单,只有要1个选中,那么一级菜单就是半选状态,非全选。
因此,提交表单参数时,也要将一级菜单的id提交过去才行。
本文参考链接:
https://element.eleme.cn/#/zh-CN/component/checkbox#jin-yong-zhuang-tai