uniapp小程序使用省市县区选择器picker
•
移动开发
框架是uview2.0
效果图:

1、下载城市文件
文件 city.js
https://www.aliyundrive.com/s/mawbBRrcbr7 密码 59ny
2、引入城市文件
文件放到项目的根目录utils文件内了

代码如下
html:
如果跟我一样是在框架的form组件中使用 且存在input输入框的情况下 可能会造成软键盘和picker同时弹出的情况 这种情况可以参考uniapp小程序点击输入框时阻止弹出软键盘
强烈建议给input标签添加disabled属性避免软键盘弹出!
js:
// 导入城市js文件
import cityData from '@/utils/city.js'
export default {
data() {
return {
cityName: "请选择省市县区",
// 城市选择器
cityShow: false,
// 打开选择器显示默认城市
cityList: [],
cityLevel1: [],
cityLevel2: [],
cityLevel3: [],
};
},
onLoad() {
// 城市选择器初始化
this.initCityData();
},
methods: {
// 城市选择器
initCityData() {
// 遍历城市js
cityData.forEach((item1, index1) => {
let temp2 = [];
this.cityLevel1.push(item1.provinceName);
let temp4 = [];
let temp3 = [];
// 遍历市
item1.cities.forEach((item2, index2) => {
temp2.push(item2.cityName);
// 遍历区
item2.counties.forEach((item3, index3) => {
temp3.push(item3.countyName);
})
temp4[index2] = temp3;
temp3 = [];
})
this.cityLevel3[index1] = temp4;
this.cityLevel2[index1] = temp2;
})
// 选择器默认城市
this.cityList.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
},
// 选中时执行
changeHandler(e) {
const {
columnIndex,
index,
indexs,
value,
values,
// 微信小程序无法将picker实例传出来,只能通过ref操作
picker = this.$refs.uPicker
} = e;
if (columnIndex === 0) { // 选择第一列数据时
// 设置第二列关联数据
picker.setColumnValues(1, this.cityLevel2[index]);
// 设置第三列关联数据
picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
} else if (columnIndex === 1) { // 选择第二列数据时
// 设置第三列关联数据
picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
}
},
// 单击确认按钮时执行
cityConfirm(e) {
// 输出数组 [省, 市, 区]
console.log(e.value);
this.cityName = e.value.join("-");
// 隐藏城市选择器
this.cityShow = false;
},
}
}
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/a2fc3b8d95.html
