前言
近期遇到一个业务场景,完成该功能花费了比较多的时间,所以记录一下。
业务场景:
- Cascader组件有三个层级;
- Cascader组件options通过接口获取,数据可以在系统中随意配置;
- 要求默认选中前3个数据,如果数据总数小于3个,则选择全部;
思路一:defaultValues的值对照options手工输入
弊端:因为options是动态获取的,并且数据可在系统中随意配置。当存在删除或新增时,就会出错。
思路二:defaultValues的值通过代码动态获取
具体思路如下:
- 根据options获取所有可选的value组合(难点);
- 使用slice方法获取前3个数据;
代码如下:
// 模拟接口请求数据
function getStoreTree () {
return new Promise(resolve => {
setTimeout(() => {
const res = {
data: [
{
"id": "1687351835205177346",
"name": "运营商1",
"children": [
{
"id": "1687351916750835714",
"name": "代理商1",
"children": [
{
"id": "1687352115179163649",
"name": "门店1",
},
{
"id": "1749724252856102913",
"name": "门店2",
},
]
}
]
},
{
"id": "1732225387189829634",
"name": "运营商2",
"children": [
{
"id": "1732225767063748610",
"name": "代理商2",
"children": [
{
"id": "1720000759574937601",
"name": "门店3",
},
]
},
{
"id": "1732230102883565570",
"name": "运营商3",
"children": [
{
"id": "1725697306186764289",
"name": "门店4",
},
{
"id": "1725697747402379265",
"name": "门店5",
},
{
"id": "1725698021235904514",
"name": "门店6",
},
]
},
]
},
]
}
resolve(res)
}, 500)
})
}
// 获取所有的可选情况
function getAllStoreValue () {
return getStoreTree().then(res => {
let result = []
let currentArr = []
function getFunc (arr, index) {
for (let item of arr) {
currentArr[index] = item.id
if (item.children && item.children.length > 0) {
getFunc(item.children, index + 1)
} else {
result.push([...currentArr])
}
}
currentArr.splice(index, 1)
}
getFunc(res.data, 0)
return result
})
}
getAllStoreValue().then(values => {
const allStoreValue = values
// 即使allStoreValue的length小于3,下述代码依然能实现需求
const defaultValues = allStoreValue.slice(0,3)
console.log(defaultValues)
})
结尾
大家有其它实现思路也可以分享在评论区。