Vue城市选择器(省市区)
读者可以参考下面的省市区三级联动代码思路,切记要仔细研究透彻,学习交流才是我们的本意,而非一成不变。切记切记!
最近又重读苏子的词,颇为感慨,愿与诸君共享一名篇
缺月挂疏桐,漏断人初静。时见幽人独往来,缥缈孤鸿影。惊起却回头,有恨无人省。拣尽寒枝不肯栖,寂寞沙洲冷。
参考代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>城市选择器</title><script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.10/vue.js"></script>
</head>
<body>
<div id="app"><select v-model="selectedProvince" @change="onProvinceChange"><option value="">请选择省份</option><option v-for="province in provinces" :value="province">{{ province }}</option></select><select v-model="selectedCity" @change="onCityChange"><option value="">请选择城市</option><option v-for="city in cities" :value="city">{{ city }}</option></select><select v-model="selectedDistrict"><option value="">请选择区县</option><option v-for="district in districts" :value="district">{{ district }}</option></select>
</div>
<script>new Vue({el: '#app',data: {selectedProvince: '',selectedCity: '',selectedDistrict: '',provinces: ['北京', '上海', '广东'], // 假设这是省份数据cities: [], // 根据所选省份动态加载的城市数据districts: [] // 根据所选城市动态加载的区县数据},methods: {onProvinceChange() {// 根据所选省份加载城市数据// 这里使用假数据,实际开发中可以通过接口获取数据if (this.selectedProvince === '北京') {this.cities = ['东城区', '西城区', '朝阳区'];} else if (this.selectedProvince === '上海') {this.cities = ['黄浦区', '徐汇区', '长宁区'];} else if (this.selectedProvince === '广东') {this.cities = ['广州市', '深圳市', '珠海市'];} else {this.cities = [];}this.selectedCity = ''; // 清空城市选择this.selectedDistrict = ''; // 清空区县选择},onCityChange() {// 根据所选城市加载区县数据// 这里使用假数据,实际开发中可以通过接口获取数据if (this.selectedCity === '东城区') {this.districts = ['东华门街道', '景山街道', '交道口街道'];} else if (this.selectedCity === '西城区') {this.districts = ['西长安街街道', '新街口街道', '月坛北街道'];} else if (this.selectedCity === '朝阳区') {this.districts = ['朝外街道', '建外街道', '劲松街道'];} else if (this.selectedCity === '黄浦区') {this.districts = ['外滩街道', '蓬莱公园街道', '南京东路街道'];} else if (this.selectedCity === '徐汇区') {this.districts = ['康健新村街道', '徐家汇街道', '湖南路街道'];} else if (this.selectedCity === '长宁区') {this.districts = ['新华路街道', '虹桥街道', '周家桥街道'];} else if (this.selectedCity === '广州市') {this.districts = ['越秀区', '海珠区', '天河区'];} else if (this.selectedCity === '深圳市') {this.districts = ['罗湖区', '福田区', '南山区'];} else if (this.selectedCity === '珠海市') {this.districts = ['香洲区', '金湾区', '斗门区'];} else {this.districts = [];}this.selectedDistrict = ''; // 清空区县选择}}});
</script>
</body>
</html>
运行效果
可以根据自己的需求添加一些新的显示