4 回复
非常感谢大佬,研究了下把想要的效果弄出来了
回复 1***@qq.com: 可以,能改就说明你很强了
在 uni-app 中实现地区三级联动(省、市、区/县)并直接显示在页面上,可以使用第三方插件或者手动实现。以下是一个手动实现的示例代码,展示了如何实现三级联动并直接显示在页面上。
首先,你需要在项目中准备好一个包含省、市、区/县数据的 JSON 文件。例如,数据结构可能如下所示:
[
{
"name": "北京市",
"children": [
{
"name": "北京市",
"children": [
{"name": "东城区"},
{"name": "西城区"},
// 更多区县
]
}
]
},
// 更多省份
]
接下来,在 pages/index/index.vue
文件中实现联动逻辑:
<template>
<view>
<picker mode="selector" :range="provinces" @change="onProvinceChange">
<view class="picker">{{ selectedProvince }}</view>
</picker>
<picker mode="selector" :range="cities" @change="onCityChange" v-if="cities.length">
<view class="picker">{{ selectedCity }}</view>
</picker>
<picker mode="selector" :range="districts" @change="onDistrictChange" v-if="districts.length">
<view class="picker">{{ selectedDistrict }}</view>
</picker>
</view>
</template>
<script>
import areas from '@/static/areas.json'; // 假设你的数据文件放在这里
export default {
data() {
return {
areas,
provinces: [],
cities: [],
districts: [],
selectedProvince: '',
selectedCity: '',
selectedDistrict: ''
};
},
mounted() {
this.provinces = this.areas.map(province => province.name);
this.selectedProvince = this.provinces[0];
this.updateCitiesAndDistricts(0);
},
methods: {
onProvinceChange(e) {
const index = e.detail.value;
this.selectedProvince = this.provinces[index];
this.updateCitiesAndDistricts(index);
},
onCityChange(e) {
const index = e.detail.value;
this.selectedCity = this.cities[index];
this.districts = this.cities[index].children.map(district => district.name);
this.selectedDistrict = this.districts[0];
},
onDistrictChange(e) {
this.selectedDistrict = this.districts[e.detail.value];
},
updateCitiesAndDistricts(provinceIndex) {
this.cities = this.areas[provinceIndex].children;
this.selectedCity = this.cities[0]?.name || '';
this.districts = this.cities[0]?.children.map(district => district.name) || [];
this.selectedDistrict = this.districts[0] || '';
}
}
};
</script>
<style>
.picker {
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
}
</style>
这段代码通过 picker
组件实现了省、市、区/县的三级联动,并将选中的值显示在页面上。areas.json
文件包含了所有的地区数据,通过 mounted
钩子函数初始化省份列表,并通过事件监听函数更新市和区/县列表。