我的需求是一级部门(学校或者学院)跟二级部门(学校或者学院的部门)的联动。
json的数据结构是:
?[ ? ? ? [{id: "1", name: "部门00A"}, {id: "2", name: "部门00B"}],
? ? ?[{id: "4", name: "保定党校", parentId: "1"}, {id: "5", name: "唐山党校", parentId: "1"},{id: "6", name: "石家庄党校", parentId: "1"},{id: "7", name: "湖北党校", parentId: "2"},{id: "8", name: "湖南党校", parentId: "2"},{id: "9", name: "海南党校", parentId: "2"}]
]
?
wxml代码:
<view class="reg-item" wx:if="{{reg == false}}">
<picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange" value="{{multiIndex}}" range="{{multiArray}}" range-key="name">
<view wx:if="{{index == 0}}" class="reg-input-p reg-picker">
请选择所属部门
</view>
<view wx:else class="reg-input reg-picker">
{{multiArray[0][multiIndex[0]].name}} {{multiArray[1][multiIndex[1]].name}}
</view>
</picker>
</view>
?js代码是:
var app = getApp();
Page({
data: {
objectMultiArray:[],
multiArray: [],
multiIndex: [0,0],
},
onLoad: function () {
this.getDepartment();
},
//获取json数据并给默认值
getDepartment() {
var that = this
app.util.request({
url: 'entry/wxapp/getdepartments',
method: 'POST',
success: function (result) {
that.setData({
objectMultiArray: result.data.data
});
//把接受的数据根据一级的默认第一个组成二级部门默认数组
that.data.multiArray[0] = that.data.objectMultiArray[0];
var i = 0,arr = [];
that.data.objectMultiArray[1].forEach(function(item){
if(that.data.objectMultiArray[0][0].id == item.parentId){
arr[i] = item;
i++;
}
})
that.data.multiArray[1] = arr;
that.setData({
multiArray: that.data.multiArray
});
}
})
},
bindMultiPickerChange(e) {
console.log('picker发送选择改变,携带值为', e)
var that = this
that.setData({
multiIndex: e.detail.value,
})
},
//picker 选择联动事件
bindMultiPickerColumnChange: function (e) {
console.log('修改的列为', e.detail.column, ',值为', e.detail.value);
let objectMultiShow = [];
var that = this;
var data = {
multiArray: this.data.multiArray,
multiIndex: this.data.multiIndex
};
data.multiIndex[e.detail.column] = e.detail.value;
//一级赋值
data.multiArray[0] = that.data.objectMultiArray[0];
//判断是否是操作一级
if(e.detail.column === 0){
var i = 0,arr = [];
//根据一级的id把二级循环赋值
that.data.objectMultiArray[1].forEach(function(item){
if(that.data.objectMultiArray[0][e.detail.value].id == item.parentId){
arr[i] = item;
i++;
}
})
data.multiArray[1] = arr;
//重新渲染数据
this.setData(data);
}
},
});
效果图
?
?
?
|