微信小程序实现省市区级联选择组件
-
首先,创建一个新的组件,命名为
area-picker
。 -
在
area-picker.wxml
文件中添加以下代码:
<view class="area-picker"><picker mode="multiSelector" bindchange="onPickerChange" bindcolumnchange="onColumnChange" value="{{pickerIndex}}" range="{{pickerData}}"><view class="picker-view">{{selectedArea || '请选择省市区'}}</view></picker>
</view>
- 在
area-picker.ts
文件中添加以下代码:
import { areaData } from './area-data';interface AreaItem {code: string;name: string;
}Component({properties: {// 可以添加自定义属性},data: {pickerData: [[], [], []] as string[][],pickerIndex: [0, 0, 0],selectedArea: '',provinces: [] as AreaItem[],cities: [] as AreaItem[],districts: [] as AreaItem[],},lifetimes: {attached() {this.initAreaData();},},methods: {initAreaData() {const provinces = areaData.map(province => ({code: province.code,name: province.name,}));this.setData({provinces,pickerData: [provinces.map(p => p.name),[],[],],});this.updateCities(0);this.updateDistricts(0);},updateCities(provinceIndex: number) {const cities = areaData[provinceIndex].children.map(city => ({code: city.code,name: city.name,}));this.setData({cities,'pickerData[1]': cities.map(c => c.name),});},updateDistricts(cityIndex: number) {const { pickerIndex } = this.data;const districts = areaData[pickerIndex[0]].children[cityIndex].children.map(district => ({code: district.code,name: district.name,}));this.setData({districts,'pickerData[2]': districts.map(d => d.name),});},onColumnChange(e: WechatMiniprogram.PickerColumnChange) {const { column, value } = e.detail;const { pickerIndex } = this.data;pickerIndex[column] = value;if (column === 0) {this.updateCities(value);this.updateDistricts(0);pickerIndex[1] = 0;pickerIndex[2] = 0;} else if (column === 1) {this.updateDistricts(value);pickerIndex[2] = 0;}this.setData({ pickerIndex });},onPickerChange(e: WechatMiniprogram.PickerChange) {const { value } = e.detail;const { provinces, cities, districts } = this.data;const selectedArea = `${provinces[value[0]].name} ${cities[value[1]].name} ${districts[value[2]].name}`;this.setData({ selectedArea });this.triggerEvent('areachange', {province: provinces[value[0]],city: cities[value[1]],district: districts[value[2]],});},},
});
- 创建
area-data.ts
文件,包含省市区数据:
export const areaData = [{code: '110000',name: '北京市',children: [{code: '110100',name: '北京市',children: [{ code: '110101', name: '东城区' },{ code: '110102', name: '西城区' },// ... 其他区],},],},// ... 其他省份
];
- 在
area-picker.wxss
文件中添加一些基本样式:
.area-picker {padding: 10px;
}.picker-view {border: 1px solid #ccc;padding: 10px;border-radius: 4px;
}
- 在页面中使用该组件:
<area-picker bind:areachange="onAreaChange" />
在对应的页面 .ts
文件中添加 onAreaChange
方法:
Page({onAreaChange(e: any) {const { province, city, district } = e.detail;console.log('Selected area:', province, city, district);},
});
这个组件实现了以下功能:
- 三级联动的省市区选择
- 选择后显示完整的地址文本
- 选择完成后触发
areachange
事件,返回选中的省市区对象
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓