el-checkbox的基本使用,避坑指南
·
el-checkbox的基本使用,避坑指南
使用el-checkbox勾选出现的问题:全选不生效,全选后底下的勾选不能回显
有问题的代码
<template>
<div>
<el-checkbox
class="all_t"
:indeterminate="isIndeterminate"
v-model="checkAll"
@change="handleCheckAllChangeSales"
>全选</el-checkbox
>
<el-checkbox-group
v-model="checkeds"
@change="handleCheckedColumnChangeSales"
>
<el-checkbox
v-for="(item,index) in detailsList"
:label="item.title"
:key="index"
>{{ item.title }}</el-checkbox
>
</el-checkbox-group>
</div>
</template>
<script>
export default {
name: 'demo',
data() {
return {
checkAll: false,
checkeds: [], // 已选数据
names: [], // 默认所有数据
isIndeterminate: false, // 全选框是否在勾选状态
detailsList: [
{
"title": "销量",
"values": [
"0",
"5"
]
},
{
"title": "销售额",
"values": [
"8",
"1"
]
},
{
"title": "订单量",
"values": [
"3",
"9"
]
},
{
"title": "退款量",
"values": [
"0",
"0"
]
}
]
}
},
created() {
this.names = this.detailsList
},
methods: {
handleCheckAllChangeSales(val) {
this.checkeds = val ? this.detailsList : [];
this.isIndeterminate = false;
},
handleCheckedColumnChangeSales(value) {
let checkedCount = value.length
this.checkAll = checkedCount === this.names.length
this.isIndeterminate = checkedCount > 0 && checkedCount < this.names.length
}
}
};
</script>
勾选出现的问题:全选不生效,全选后底下的勾选不能回显,排查问题中发现打印this.checkeds能得到数据,全选和反选数据都能得到。
一开始认为是结构中key的渲染,但是试过后发现 :key="index"还是:key="item.title"都不会影响回显。
仔细阅读官网发现this.checkedCities的数据结构不能那么复杂
所以我在handleCheckAllChangeSales方法中把过滤原来的this.detailsList 数,当全选时赋值给this.checkeds
this.checkeds打印出来这个值是这种结构
最终实现效果
所有代码
<template>
<div>
<el-checkbox
class="all_t"
:indeterminate="isIndeterminate"
v-model="checkAll"
@change="handleCheckAllChangeSales"
>全选</el-checkbox
>
<el-checkbox-group
v-model="checkeds"
@change="handleCheckedColumnChangeSales"
>
<el-checkbox
v-for="(item) in detailsList"
:label="item.title"
:key="item.title"
>{{ item.title }}</el-checkbox
>
</el-checkbox-group>
</div>
</template>
<script>
export default {
name: 'demo',
data() {
return {
checkAll: false,
checkeds: [], // 已选数据
names: [], // 默认所有数据
isIndeterminate: false, // 全选框是否在勾选状态
detailsList: [
{
"title": "销量",
"values": [
"0",
"5"
]
},
{
"title": "销售额",
"values": [
"8",
"1"
]
},
{
"title": "订单量",
"values": [
"3",
"9"
]
},
{
"title": "退款量",
"values": [
"0",
"0"
]
}
]
}
},
created() {
this.names = this.detailsList
},
methods: {
handleCheckAllChangeSales(val) {
var checkedsItem = val ? this.detailsList : []
if (checkedsItem.length > 0) {
checkedsItem.map(item => {
this.checkeds.push(item.title)
})
} else {
this.checkeds = []
}
this.isIndeterminate = false
},
handleCheckedColumnChangeSales(value) {
let checkedCount = value.length
this.checkAll = checkedCount === this.names.length
this.isIndeterminate = checkedCount > 0 && checkedCount < this.names.length
}
}
};
</script>
更多推荐
已为社区贡献3条内容
所有评论(0)