首先获取所有的省份数据,在点击省份过后加载该省下所有市级数据,点击市加载该市下所有县级数据,利用el-cascade的active-item-change事件实现动态拉取下级选项
<el-cascader v-model="projectInfo.position" placeholder="请选择省市县" style="width: 100%" :options="provinceList" @active-item-change="handleItemChange" :props="props"></el-cascader>
//data
provinceList: [], //省市县列表
props: {value: 'value', children: 'cities'},
后台接口设计——不传值返回所有省份数据,传省份id(province_id)返回该省份下所有市级数据,传省份id(province_id)和市区id(city_id)返回该市下所有县级数据
getPosition(val, cb) {
let vm = this; //查询省市县
let params = {};
if(!val) { //初始化加载 获取所有省份数据
params = {}
} else if (val.length === 1) { //加载二级 获取市级数据
params = {province_id: val[0]}
} else { //加载3级 获取县级数据
params = {province_id: val[0], city_id: val[1]}
}
Https.queryPosition(params).then((res) => {
if(!val) { //初始化加载 查询省份数据
vm.provinceList = res.data.map((e) => {
return {value: e.province_id, label: e.province_name, cities: []}
});
} else if (val.length === 1) { //加载二级 查询该省下市级数据
vm.provinceList.map((item) => {
if(item.value === val[0]) {
item.cities = res.data.map((e) => {
return {value: e.city_id, label: e.city_name, cities: []}
})
}
})
} else { //加载3级 查询该省市下县级数据
vm.provinceList.map((item) => {
if(item.value === val[0]) {
item.cities.map((value) => {
if(value.value === val[1]){
value.cities = res.data.map((e) => {
return {value: e.county_id, label: e.county_name}
})
}
})
}
})
}
cb&&cb(res);
}).catch((err => {
console.log(err);
}))
},
handleItemChange (val) {
this.getPosition(val)
},
获取初始状态,当级联选择器有初始数据时,需要渲染初始数据,后台返回初始数据为:
projectData:{
province_id: 1, //省
city_id: 1, //市
county_id: 1 //县
}
this.projectInfo.position = [];
this.getPosition(null,()=>{
this.projectInfo.position.push(this.projectData.province_id);
this.getPosition(this.projectInfo.position, ()=>{
this.projectInfo.position.push(this.projectData.city_id);
this.getPosition(this.projectInfo.position,() => {
this.projectInfo.position.push(this.projectData.county_id);
})
});
});