The uniapp applet uses the province, city, county, district selector picker

The frame is uview2.0

Renderings:

1. Download the city file

file  city.js    password m1y8

2. Import city files

The file is placed in the utils file in the root directory of the project

code show as below

html:

If it is used in the form component of the framework like me and there is an input input box, it may cause the soft keyboard and picker to pop up at the same time. In this case, you can refer to the uniapp applet to prevent the soft keyboard from popping up when the input box is clicked .

It is strongly recommended to add the disabled attribute to the input tag to prevent the soft keyboard from popping up!

<u--form labelPosition="left">
    <u-form-item label="省市县区:" borderBottom labelWidth="70" @tap="cityShow = true">
	    <u--input v-model="cityName" border="none" placeholder="请选择省市县区"></u--input>
	    <!-- 城市选择 -->
	    <u-picker :show="cityShow" ref="uPicker" :columns="cityList" @confirm="cityConfirm" 
        @change="changeHandler" @cancel="cityShow = false"></u-picker>
    </u-form-item>
</u--form>

js: 

<script>
	// 导入城市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;
			},
		}
	}
</script>

Guess you like

Origin blog.csdn.net/weixin_46607967/article/details/129166568