我提供一个省市区的数据源的接口(www.test.com/code),返回参数,有code,data,当code等于0,即返回成功,data存储的是地区数据,你根据这个再写一次
时间: 2024-04-04 13:31:26 浏览: 7
好的,我可以根据您提供的接口再写一次省市区三级联动的Vue组件。以下是代码示例:
```vue
<template>
<div>
<select v-model="selectedProvince" @change="provinceChanged">
<option value="">请选择省份</option>
<option v-for="province in provinces" :value="province">{{province.name}}</option>
</select>
<select v-model="selectedCity" @change="cityChanged">
<option value="">请选择城市</option>
<option v-for="city in cities" :value="city">{{city.name}}</option>
</select>
<select v-model="selectedDistrict">
<option value="">请选择区县</option>
<option v-for="district in districts" :value="district">{{district.name}}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
provinces: [], // 省份列表
cities: [], // 城市列表
districts: [], // 区县列表
selectedProvince: '', // 当前选中的省份
selectedCity: '', // 当前选中的城市
selectedDistrict: '' // 当前选中的区县
};
},
mounted() {
// 获取省份列表
this.getProvinces();
},
methods: {
// 获取省份列表
getProvinces() {
const url = 'www.test.com/code';
this.$http.get(url).then(response => {
if (response.data.code === 0) {
this.provinces = response.data.data;
}
});
},
// 获取城市列表
getCities(province) {
const url = 'www.test.com/code?province=' + province.id;
this.$http.get(url).then(response => {
if (response.data.code === 0) {
this.cities = response.data.data;
}
});
this.selectedCity = ''; // 清空选中的城市
this.selectedDistrict = ''; // 清空选中的区县
},
// 获取区县列表
getDistricts(city) {
const url = 'www.test.com/code?city=' + city.id;
this.$http.get(url).then(response => {
if (response.data.code === 0) {
this.districts = response.data.data;
}
});
this.selectedDistrict = ''; // 清空选中的区县
},
// 省份改变事件
provinceChanged() {
const province = this.selectedProvince;
if (province) {
this.getCities(province);
} else {
this.cities = [];
this.districts = [];
this.selectedCity = '';
this.selectedDistrict = '';
}
},
// 城市改变事件
cityChanged() {
const city = this.selectedCity;
if (city) {
this.getDistricts(city);
} else {
this.districts = [];
this.selectedDistrict = '';
}
}
}
};
</script>
```
以上代码实现了一个使用接口获取省市区数据的Vue组件。当用户选择省份时,将自动根据接口获取该省份的城市列表并显示在第二个下拉框中;当用户选择城市时,将自动根据接口获取该城市的区县列表并显示在第三个下拉框中。