通过picker-view组件实现的省市区三级联动

88 阅读1分钟

代码中已将其 组件化,使用的是静态的数据,也可以动态进行获取

实现如下图

image.png

代码如下

<template>
	<view class="region-box">
		<picker-view :value="region" @change="bindChange">
			<picker-view-column>
				<view class="center" v-for="(item, index) in regionList" :key="index">
					{{ item.name }}
				</view>
			</picker-view-column>
			<picker-view-column v-if="regionList[region[0]]">
				<view class="center" v-for="(item, index) in regionList[region[0]].city" :key="index">
					{{ item.name }}
				</view>
			</picker-view-column>
			<picker-view-column v-if="regionList[region[0]]">
				<view class="center"
					v-for="(item, index) in regionList[region[0]].city[region[1]].area" :key="index">
					{{ item }}
				</view>
			</picker-view-column>
		</picker-view>

		<view style="width: 100%;" class="btn-Block center">
			<view class="btn-left center" @click="onCancel">取消</view>
			<view class="btn-right center" @click="onSubmit">
				确定
			</view>
		</view>
	</view>
</template>

<script>
	import { data } from '../region.js'		//引入的省市区静态数据文件
	export default {
		name:"levelLinkage",
		created() {
			this.regionList = data
		},
		data() {
			return {
				region: [0, 0, 0],	//地址每列的index
				regionList: [],		//地址数据,格式为 三级地址全返回
				regionText: ''
			};
		},
		methods: {
			//选择值改变事件
			bindChange(e) {
				// 用于对比滑动的是哪一列数据
				const val = e.detail.value
				if(this.region[0] !== val[0]) {
					// 如果滑动的是第一列数据,让二三列恢复到0
					this.region = [val[0], 0, 0]
				} else if(this.region[1] !== val[1]) {
					// 滑动的是第二列数据
					this.region = [val[0], val[1], 0]
				} else {
					this.region = e.detail.value;
				}
			},
			//确定按钮操作
			onSubmit: function() {
				this.regionText = this.regionList[this.region[0]].name + ' ' + this.regionList[this.region[0]]
					.city[this.region[1]].name + ' ' + this.regionList[this.region[0]].city[this.region[1]]
					.area[this.region[2]]
				console.log(this.regionText)
			},
			onCancel() {
				// 调用父组件方法关闭
				this.$emit('onCancel')
			}
		}
	}
</script>

<style lang="scss" scoped>
.region-box {
	background-color: #FFFFFF;

	.center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.btn-Block {
		width: 100%;
		background-color: #FFFFFF;
		padding: 25upx;
		height: 230upx;

		.btn-left {
			width: 250upx;
			height: 80upx;
			border-radius: 10upx;
			color: #289CFD;
			background-color: rgba(153, 153, 153, 0.2);
			margin-right: 30upx;
		}

		.btn-right {
			width: 250upx;
			height: 80upx;
			border-radius: 10upx;
			color: #FFFFFF;
			background-color: #289CFD;
		}
	}

	.picker-view {
		background-color: #FFFEFD;
	}

	picker-view {
		width: 100%;
		height: 600upx;
	}

</style>