亲测有效!!!
:options="cascaderOptions",自己组装options是回显的关键!!!
要确认组装的数据格式是label、和value,要么就要在props设置对应关系!!!
<template>
<el-cascader
v-model="areaIds"
:options="cascaderOptions"
:props="cascaderProps"
@change="handleAreaChange"
size="mini"
></el-cascader>
</template>
<script>
import { getChildAreaList } from "../api.js";
export default {
name: "demo",
data() {
return {
areaIds: [],
//四级地址级联选择器--回显所需模板
cascaderOptions: [],
// 行政区级联选择
cascaderProps: {
// checkStrictly: true, //可选任意层级
emitPath: true,
expandTrigger: "hover",
label: "name", // 重要--回显时组装的options要对应上
value: "areaId", // 重要--回显时组装的options要对应上
lazy: true,
lazyLoad: (node, resolve) => {
// const { value, level } = node;
const { value } = node;
getChildAreaList({
areaId: value || 4744,
})
.then((res) => {
if (res.success && res.data) {
resolve(res.data);
} else {
resolve([]);
}
})
.catch((err) => {
resolve();
console.log(err);
});
},
},
};
},
created() {
const { provinceId, cityId, countryId, townId, } = this.addrInfo;
this.areaIds = townId
? [provinceId, cityId, countryId, townId]
: [provinceId, cityId, countryId];
this.initOptions(provinceId, cityId, countryId, townId); //为回显数据所准备--四级地址options模板
},
methods: {
//为回显数据所准备--四级地址options模板
async initOptions(provinceId, cityId, countyId, townId) {
if (!provinceId) {
return;
}
let fns = [
getChildAreaList({ areaId: 4744 }), //所有省份list
getChildAreaList({ areaId: provinceId }), //指定省份下的 城市list
getChildAreaList({ areaId: cityId }), //指定省份、城市下的 县list
// getChildAreaList({ areaId: countyId }), //指定省份、城市、县下的 乡镇list
];
if (townId) {
fns.push(getChildAreaList({ areaId: countyId }));
}
const results = await Promise.all(fns);
const [res1, res2, res3] = results;
if (res1.success && res2.success && res3.success) {
this.cascaderOptions = res1.data.map((province) => {
if (province.areaId === provinceId) {
province.children = res2.data.map((city) => {
if (city.areaId === cityId) {
city.children = res3.data.map((county) => {
if (townId && results[3].success) {
if (county.areaId === countyId) {
county.children = results[3].data.map((town) => {
return {
...town,
leaf: true,
};
});
}
return county;
} else {
return {
...county,
leaf: true,
};
}
});
}
return city;
});
}
return province;
});
console.log(this.cascaderOptions);
}
},
},
};
</script>
网友评论