uni-app 省市區(qū)仿element ui Cascader 級聯(lián)選擇器數(shù)據(jù)格式

需求: pc端是用的element框架,H5和微信端是uni-app框架,所以數(shù)據(jù)是統(tǒng)一的,但是uni-app省市區(qū)是分開的數(shù)據(jù),我的天,找了別人寫的插件,各種實現(xiàn),各種格式數(shù)據(jù),花里胡哨,但是卻沒我想要的(或許有但是代碼看的頭疼)。所以就自己改裝了官網(wǎng)的一套,但是這只是我的業(yè)務(wù),
所以還是建議自己去專心研究實現(xiàn)屬于自己的組件(靜下心來啥都會)。

實現(xiàn)思路: 1. 根據(jù) "huilderX登錄模板"那套模塊改裝,先的知道他的數(shù)據(jù)格式,省[{}], 市 [[{}]], 區(qū) [[[{}]]] ,篩選的數(shù)據(jù), 通過index找到對應(yīng)的對象。

2.把Cascader 級聯(lián)選擇器數(shù)據(jù)拆分成省、市、區(qū)三個對象

// 分離省、市、區(qū)

filters(datas) {

let province = []? //省

let citys = []? // 市

let areas = [] // 區(qū)

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.根據(jù)后臺返回的省市區(qū)id找到對應(yīng)的index
// 省的id轉(zhuǎn)索引

? let a = this.province.findIndex(item=> item.value == newval[0])

const city = JSON.parse(JSON.stringify(this.city))

this.sum = newval[1]

// 市的id轉(zhuǎn)索引

let b = this.flatten(city, newval[1])

const area = JSON.parse(JSON.stringify(this.area))

// 區(qū)的id轉(zhuǎn)索引

let c = this.flatten(area, newval[2])

this.pickerValueDefault = [a,b,c]


// 將市、區(qū)key轉(zhuǎn)成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

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容