element UI Cascader 级联选择器 动态加载

时间:2024-04-14 08:07:14

先看下效果图
element UI Cascader 级联选择器 动态加载

直接上代码

div部分
element UI Cascader 级联选择器 动态加载
data部分
element UI Cascader 级联选择器 动态加载

methods代码部分
// 获取省
getProvence(_this, param) {
this.$api.AreaAddress(_this, param).then(res => { //你的接口
this.provenceArray = res.data; //赋值给provenceArray
this.provenceArray.forEach((item, index) => {
this.$set(this.provenceArray[index], “cities”, []); // 用this.$set刷新provenceArray
});
});
},
// 利用active-item-change事件,可以在用户点击某个省份时拉取该省份下的城市数据
handleItemChange(val) {
let areaLevel = “”;
let value = “”;
let that = this;
if (val.length == 1) {
value = val[0];
areaLevel = 2;
this.provenceArray.map(function(v, a) {
if (v.areaId == value) {
that.p1 = a;//这里是取你选中第一层的第几个
}
});
}
if (val.length == 2) {
value = val[1];
areaLevel = 3;
this.provenceArray[that.p1].cities.map(function(v, a) {
if (v.areaId == value) {
that.p2 = a;//这里是取你选中第二层的第几个
}
});
}
let param = {
areaLevel: areaLevel,
areaId: value
};
if (areaLevel == 2) {
this.$api.AreaAddress(this, param).then(res => {
let cities = res.data;
cities.map(function(v, a) {
v[“cities”] = [];//如果想要下一级,这里cities要设置为[]
});
this.provenceArray.map(function(v, a) {
if (v.areaId == val) {
v.cities = cities;
}
});
this.$set(this.provenceArray, “provenceArray”, this.provenceArray);
});
}
if (areaLevel == 3) {
this.$api.AreaAddress(this, param).then(res => {
let cities = res.data;
this.provenceArray[that.p1].cities[that.p2].cities = cities;
this.$set(this.provenceArray, “provenceArray”, this.provenceArray);
});
}
},
个人觉得代码肯定有可以简化的部分,不过先完成目标。