vue 封装一个四级联动组件
时间: 2023-10-29 21:52:55 浏览: 39
好的,我可以给您提供一个简单的四级联动组件的封装示例代码,您可以根据自己的需求进行修改和优化。
```html
<template>
<div>
<select v-model="selectedProvince" @change="onProvinceChange">
<option value="">请选择省份</option>
<option v-for="province in provinces" :value="province">{{ province.name }}</option>
</select>
<select v-model="selectedCity" :disabled="!selectedProvince" @change="onCityChange">
<option value="">请选择城市</option>
<option v-for="city in cities" :value="city">{{ city.name }}</option>
</select>
<select v-model="selectedDistrict" :disabled="!selectedCity" @change="onDistrictChange">
<option value="">请选择区县</option>
<option v-for="district in districts" :value="district">{{ district.name }}</option>
</select>
<select v-model="selectedStreet" :disabled="!selectedDistrict">
<option value="">请选择街道</option>
<option v-for="street in streets" :value="street">{{ street.name }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
provinces: [], // 所有的省份
cities: [], // 当前省份下的所有城市
districts: [], // 当前城市下的所有区县
streets: [], // 当前区县下的所有街道
selectedProvince: null, // 当前选中的省份
selectedCity: null, // 当前选中的城市
selectedDistrict: null, // 当前选中的区县
selectedStreet: null // 当前选中的街道
};
},
mounted() {
// 加载所有的省份
this.loadProvinces();
},
methods: {
// 加载所有的省份
loadProvinces() {
// TODO: 发送请求获取所有的省份数据
this.provinces = [
{ code: "110000", name: "北京市" },
{ code: "120000", name: "天津市" },
{ code: "130000", name: "河北省" },
{ code: "140000", name: "山西省" },
{ code: "150000", name: "内蒙古自治区" }
];
},
// 加载当前省份下的所有城市
loadCities() {
// TODO: 发送请求获取当前省份下的所有城市数据
this.cities = [
{ code: "110100", name: "北京市" },
{ code: "120100", name: "天津市" },
{ code: "130100", name: "石家庄市" },
{ code: "130200", name: "唐山市" },
{ code: "130300", name: "秦皇岛市" }
];
},
// 加载当前城市下的所有区县
loadDistricts() {
// TODO: 发送请求获取当前城市下的所有区县数据
this.districts = [
{ code: "110101", name: "东城区" },
{ code: "110102", name: "西城区" },
{ code: "110105", name: "朝阳区" },
{ code: "110106", name: "丰台区" },
{ code: "110107", name: "石景山区" }
];
},
// 加载当前区县下的所有街道
loadStreets() {
// TODO: 发送请求获取当前区县下的所有街道数据
this.streets = [
{ code: "110101001", name: "东华门街道" },
{ code: "110101002", name: "景山街道" },
{ code: "110101003", name: "交道口街道" },
{ code: "110101004", name: "安定门街道" },
{ code: "110101005", name: "北新桥街道" }
];
},
// 省份变化时更新城市列表和区县列表
onProvinceChange() {
this.selectedCity = null;
this.selectedDistrict = null;
this.selectedStreet = null;
if (this.selectedProvince) {
this.loadCities();
this.cities = [];
this.districts = [];
this.streets = [];
}
},
// 城市变化时更新区县列表和街道列表
onCityChange() {
this.selectedDistrict = null;
this.selectedStreet = null;
if (this.selectedCity) {
this.loadDistricts();
this.districts = [];
this.streets = [];
}
},
// 区县变化时更新街道列表
onDistrictChange() {
this.selectedStreet = null;
if (this.selectedDistrict) {
this.loadStreets();
this.streets = [];
}
}
}
};
</script>
```
以上代码仅供参考,实际上,您需要根据自己的需求来进行修改和完善。例如,您可以将数据请求等方法单独封装到一个 `service` 文件中,让代码更加清晰易读。