用户反馈需要加一个地区全选的功能,他们需要先全选,然后在去掉其中几个地区
效果图:
我也想过把全选地区放进去,但是没有达到想要的效果,这就尴尬了,等用户先用着吧,后面相处办法了就回来更新
实现代码:
<template>
<div class="container">
<div>
<el-checkbox v-model="regionTotal" @change="getRegionTotal">全选地区</el-checkbox>
</div>
<el-cascader v-model="regionValue" :options="options" @change="changeRegionLength" :props="propsRegion"
v-loading="regionLoading" clearable filterable style="width: 500px;"></el-cascader>
</div>
</template>
<script>
export default {
data() {
return {
regionTotal: false, // 地区全选按钮
options: [], // 地区接口数据
regionValue: [], // 选中发送给后台的地区数据id
regionValueSwap: [], // 获取地区数据的中间数组,直接用el-cascader数据会不更新视图
regionLoading: false, //loading
regionLength: 0, //用于判断全选按钮true或者false,如果等于地区数据长度,全选按钮为true
propsRegion: { //自己看element文档https://element.eleme.cn/#/zh-CN/component/cascader
multiple: true,
value: 'id',
label: 'name',
leaf: 'parent',
emitPath: false
},
}
},
methods: {
/**
* 通过递归方法获取地区id,未知children,三级联动总不可能有人用forfor吧
* 判断这个数组下面还有没有children数组
* 存在children存在继续递归,不存在则push id
* */
recursiveRegion(regionList) {
for (let i = 0; i < regionList.length; i++) {
if (typeof(regionList[i].children) != 'undefined') {
this.recursiveRegion(regionList[i].children)
} else {
this.regionValueSwap.push(regionList[i].id)
}
}
},
// 地区全选
getRegionTotal() {
// 判断是不是全选了true全选数据
if (this.regionTotal == true) {
this.recursiveRegion(this.options)
// 过滤重复的地区数据,执行多了一次,回调每个执行多了一次判断
this.regionValueSwap = [...new Set(this.regionValueSwap)]
this.regionValue = this.regionValueSwap
// 获取数据长度,用于判断是否全选
this.regionLength = this.regionValueSwap.length
} else {
// false清空数据
this.regionValue = []
}
},
// 如果不是全选了,全选的true变更为false
changeRegionLength() {
if (this.regionLength != this.regionValue.length) {
this.regionTotal = false
} else {
this.regionTotal = true
}
},
//获取地区接口数据
appointRegion() {
this.regionLoading = true
this.$axios.post('/api/v1/accountAuth/regionList1').then(res => {
this.regionLoading = false
if (res.data.code != 0) return this.$message.error(res.data.message)
// 接口地区数据
this.options = res.data.data.data
}).catch(err => {
this.regionLoading = false
this.$message.error('内部服务器错误,请联系管理员')
})
},
},
created() {
this.appointRegion()
}
};
</script>
<style lang="scss">
.container {
padding: 50px;
background-color: white;
height: 100%;
}
</style>
接口的数据格式:
当然,现在这是传全部的子节点给后台的,如果想知道子节点全选了只传它的父节点,请看我另一个文章,还有它父节点的逆向选择全部子节点,等我想什么更新在更新吧