需求: pc端是用的element框架,H5和微信端是uni-app框架,所以數據是統一的,但是uni-app省市區是分開的數據,我的天,找了別人寫的插件,各種實現,各種格式數據,花里胡哨,但是卻沒我想要的(或許有但是代碼看的頭疼)。所以就自己改裝了官網的一套,但是這只是我的業務,
所以還是建議自己去專心研究實現屬于自己的組件(靜下心來啥都會)。
實現思路: 1. 根據 "huilderX登錄模板"那套模塊改裝,先的知道他的數據格式,省[{}], 市 [[{}]], 區 [[[{}]]] ,篩選的數據, 通過index找到對應的對象。
2.把Cascader 級聯選擇器數據拆分成省、市、區三個對象
// 分離省、市、區
filters(datas) {
let province = []? //省
let citys = []? // 市
let areas = [] // 區
for(let i = 0; i < datas.length; i ++ ) {
province.push({"label": datas[i].label, "value": datas[i].value})
if(datas[i].children) {
let childDatas =? datas[i].children
? let city = []
let area = []
for(let j = 0; j < childDatas.length; j ++ ) {
city.push({"label": childDatas[j].label, "value": childDatas[j].value})
if(childDatas[j].children) {
let childsNuxtDatas = childDatas[j].children
? ? let areaChild = []
for(let k =0; k < childsNuxtDatas.length; k ++ ) {
? areaChild.push({"label": childsNuxtDatas[k].label, "value": childsNuxtDatas[k].value})
}
area.push(areaChild)
}
}
areas.push(area)
citys.push(city)
}
}
this.province = [...province]
this.city = [...citys]
this.area = [...areas]
},
3.根據后臺返回的省市區id找到對應的index
// 省的id轉索引
? let a = this.province.findIndex(item=> item.value == newval[0])
const city = JSON.parse(JSON.stringify(this.city))
this.sum = newval[1]
// 市的id轉索引
let b = this.flatten(city, newval[1])
const area = JSON.parse(JSON.stringify(this.area))
// 區的id轉索引
let c = this.flatten(area, newval[2])
this.pickerValueDefault = [a,b,c]
// 將市、區key轉成index
flatten(arr,sum) {
arr.forEach((item,index)=>{
? ? if(item[0] instanceof Array) {
? ? this.flatten(item,sum)
? ? } else {
if(item instanceof Array) {
let indexs =item.findIndex(list=> {
? return list.value == sum
})
if(parseInt(indexs) >= 0) {
console.log(indexs)
this.sum = indexs
}
}
}
})
? return this.sum
}