以下是省市区三级联动代码,可直接使用:
<template>
<el-form :model="formData">
<el-form-item prop="area" label="所在城市:">
<el-select
filterable
placeholder="请选择省"
v-model="formData.province"
@change="changeCity('')"
>
<el-option
v-for="(item, index) in newAllcity.province"
:value="item.name"
:key="index"
></el-option>
</el-select>
<span> - </span>
<el-select
filterable
placeholder="请选择市"
v-model="formData.city"
@change="changeArea('')"
>
<el-option
v-for="(item, index) in newAllcity.city"
:value="item.name"
:key="index"
></el-option>
</el-select>
<span> - </span>
<el-select filterable placeholder="请选择区" v-model="formData.area">
<el-option
v-for="(item, index) in newAllcity.area"
:value="item.name"
:key="index"
></el-option>
</el-select>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
newAllcity: {
province: [],
city: [],
area: [],
},
formData: {
province: "",
city: "",
area: "",
},
};
},
methods: {
async init() {
await this.getCityList(),
await this.changeCity(this.formData.city);
await this.changeArea(this.formData.area);
},
getCityList() {
return getData({
microservices: "lmall/config/getRegin",
}).then((res) => {
if (res.data.ret == 200) {
let city = res.data.data.filter((item) => item.name != "全国");
this.newAllcity.province = city;
} else {
this.$message({ message: res.data.msg });
}
});
},
changeCity(city = "") {
this.formData.city = city;
this.formData.area = '';
this.newAllcity.area = []
const province = this.newAllcity.province.filter((p) => p.name === this.formData.province)[0];
this.newAllcity.city = province ? province.children : [];
},
changeArea(area = "") {
this.formData.area = area;
const city = this.newAllcity.city.filter((p) => p.name === this.formData.city)[0];
this.newAllcity.area = city ? city.children : [];
},
},
};
</script>