写小程序遇到个问题,要求自定义3级联动的数据,但是目前小程序的联动组件还不支持,那就自己写一个,用的是多列选择器(mode = multiSelector),核心思想就是把格式化后的数据放在objectMultiArray的第一个数组里,当用户滚动第一列数据时,第一列的children是第二列要展示的内容,第二列的children是第三列要展示的内容,只要对应取出就可以, 代码如下。
<picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange" range-key="name" value="{{multiIndex}}" range="{{objectMultiArray}}">
<view class="picker">
{{objectMultiArray[0][multiIndex[0]].name}},{{objectMultiArray[1][multiIndex[1]].name}},{{objectMultiArray[2][multiIndex[2]].name}}
</view>
</picker>
var areaList = {
1:{id:10,name:'北京市', children:[{ id:101, name:'北京市', children:[{id:1011, name:'东城区',children:[]},{id:1012, name:'昌平区',children:[]},{id:1013, name:'石景山区',children:[]}]}]},
2:{id:20,name:'天津市', children:[{ id:201, name:'天津市', children:[{id:2011, name:'武清区',children:[]},{id:2012, name:'静海区',children:[]},{id:2013, name:'红桥区',children:[]}]}]}
}
Page({
data: {
objectMultiArray: [[], [], []],
multiIndex: [0, 0, 0],
},
onShow:function(){
// 首先通过接口获取自定义的数据 这里简单获取
this.setData({
objectMultiArray:this.formatArea(areaList)
})
},
// 后端返回的结构并不是想要的,要格式化
formatArea:function(area){
areaList = [[], [], []]
for(let key in area){
areaList[0].push({id:area[key].id,name:area[key].name,children:area[key].children})
}
areaList[1] = areaList[0][0].children
areaList[2] = areaList[1][0].children
return areaList
},
bindMultiPickerColumnChange: function (e) {
console.log('修改的列为', e.detail.column, ',值为', e.detail.value);
let data = {
objectMultiArray: this.data.objectMultiArray,
multiIndex: this.data.multiIndex
};
data.multiIndex[e.detail.column] = e.detail.value;
switch (e.detail.column) {
case 0: // 第一列 省
data.objectMultiArray[0].forEach((value, i)=>{
if(data.multiIndex[0] == i){
data.objectMultiArray[1] = value.children
data.objectMultiArray[2] = value.children[0].children
}
})
data.multiIndex[1] = 0;
data.multiIndex[2] = 0;
break;
case 1: // 第二列 市
data.objectMultiArray[1].forEach((value, i)=>{
if(data.multiIndex[1] == i){
data.objectMultiArray[2] = value.children
}
})
data.multiIndex[2] = 0;
break;
}
this.setData(data);
},
bindMultiPickerChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
multiIndex: e.detail.value
})
let objectMultiArray = this.data.objectMultiArray
let multiIndex = this.data.multiIndex
// 下面输出的内容就是你选择的省、市、区
console.log(objectMultiArray[0][multiIndex[0]],objectMultiArray[1][multiIndex[1]],objectMultiArray[2][multiIndex[2]])
},
})