html:
{{ provinceName }}——{{ cityName }}
js
初始化:
// 二位数组
multiArray: [[], []],
multiIndex: [0, 0],
// 后台数据
"areaList": [
{ "code": "001", "level": 1, "name": "广东省", "list": [ { "code": "001001", "level": 2, "name": "广州市",} ] },
{ "code": "110", "level": 1, "name": "北京市", "list": [ { "code": "110100", "level": 2, "name": "北京市"} ] }
]
// 转换格式
const formatAreaList = (areaList) => {
let provinceArr = [];
let cityArrObj = {};
areaList.forEach((item, index) => {
if (item.level === 1) {
provinceArr.push(item.name);
let cityArr = item.list.map(i => {
return i.name
})
cityArrObj[item.name] = cityArr
}
})
console.log(provinceArr,cityArrObj)
return {
provinceArr,
cityArrObj
}
}
事件实现:
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let {
provinceArr,
cityArrObj
} = formatAreaList(areaList)
that.setData({
areaList,
provinceArr,
cityArrObj
})
// 调整二级联动数据结构
that.adjustAreaList()
},
// 调整二级联动数据结构
adjustAreaList() {
let that = this
let {
areaList,
multiArray,
provinceName,
multiIndex,
cityName,
provinceArr,
cityArrObj
} = that.data
if (provinceName && cityName) {
// 存在则自动定位到相应的省市
this.setData({
multiArray: [provinceArr, cityArrObj[provinceName]],
multiIndex: [provinceArr.indexOf(provinceName), cityArrObj[provinceName].indexOf(cityName)]
})
} else {
// 默认第一个
that.setData({
multiArray: [provinceArr, cityArrObj[provinceArr[0]]],
multiIndex: [0, 0]
})
console.log('默认第一个', multiArray, multiIndex)
}
},
// 确定选择器的选择
bindMultiPickerChange: function (e) {
let that = this
console.log('picker发送选择改变,携带值为', e.detail.value)
that.setData({
multiIndex: e.detail.value
})
},
// 选择器滚动中
bindMultiPickerColumnChange(e) {
let that = this
let {
areaList,
multiArray,
multiIndex
} = that.data
let col = e.detail.column
let val = e.detail.value
multiIndex[col] = val
switch (col) {
case 0:
for (let i = 0; i < areaList.length; i++) {
switch (multiIndex[0]) {
case i:
let addressArray = []
for (let j = 0; j < areaList[i].list.length; j++) {
addressArray.push(areaList[i].list[j].name)
}
multiArray[1] = addressArray
break
}
}
multiIndex[0] = val
multiIndex[1] = 0
that.setData({
multiIndex,
multiArray
})
}
},
// 取消选择
cancelPicker() {
console.log('取消选择器');
let {
provinceArr,
cityArrObj,
provinceName,
cityName
} = this.data
this.setData({
multiArray: [provinceArr, cityArrObj[provinceName]],
multiIndex: [provinceArr.indexOf(provinceName), cityArrObj[provinceName].indexOf(cityName)]
})
},