<van-popup show="{{ area.show }}" round position="bottom">
<van-cascader
wx:if="{{ area.show }}"
value="{{ area.cascaderValue }}"
title="请选择户籍所在地"
options="{{ area.options }}"
field-names="{{ area.fieldNames }}"
bind:close="areaClose"
bind:change="areaChange"
bind:finish="areaFinish"
/>
</van-popup>
area: {
show: true,
cascaderValue: [],
options: [], // 初始化时只加载省份
fieldNames: {
text: 'name',
value: 'id',
children: 'children'
},
},
onLoad: function (options) {
this.loadProvinces();
},
loadProvinces: async function () {
const provinces = await this.getArea('province');
this.setData({
'area.options': provinces,
'area.cascaderValue': [] // 重置级联选择器的值
});
},
async getArea(type, parentID, cityID) {
console.log(type);
const res = await api.http({
url: '/apply/getArea',
data: {
type: type,
province_id: type === 'city' ? parentID : null,
city_id: type === 'area' ? parentID : null,
token: wx.getStorageSync('token')
}
});
return res.data.map(area => ({
...area,
children: [] // 初始化子项为空数组
}));
},
async areaChange(e) {
console.log(e.detail);
const {
value: id,
tabIndex
} = e.detail;
console.log(id);
if (tabIndex < 2) {
const nextType = ['city', 'area'][tabIndex];
const newArea = await this.getArea(nextType, id);
// 获取this.data.area.options中对应的id的下标
const selectedIndex = this.data.area.options.findIndex(option => option.id === id);
console.log(selectedIndex);
let that = this;
this.setData({
[`area.options[${selectedIndex}].children`]: newArea,
});
}
},
每次获取省/市/区都需要走一下getArea函数