解析:https://element.eleme.io/#/zh-CN/component/cascader
通过lazyload来设置加载数据源的方法
HTML
<el-cascader v-model="selectedOptions" class="input-width-250" size="small" :options="options" @change="handleChooseAddressChange" :props="props"/>
JS
一、
import { getArea } from '@/api/shop';
let initProvinceCode = '';
二、
options: '',
selectedOptions: ['广东省', '广州市', '荔湾区'], // 选择的地址默认
// 省市区
props: {
lazy: true,
lazyLoad(node, resolve) {
let that = this;
const {
level,
label
} = node;
setTimeout(() => {
if (level === 1) {
// 加载市
node.children = []; //防止加载重复数据
this.provinceName = label;
let data = {
provinceName: label,
type: 2
};
getArea(data).then(res => {
resolve(res.data);
});
} else if (level === 2) {
// 加载区
node.children = [];
let data = {
provinceName: this.provinceName || initProvinceCode,
code: label,
type: 3
};
getArea(data).then(res => {
res.data.forEach(el => {
el.leaf = level >= 2; //取消最后一级箭头
});
resolve(res.data);
});
}
}, 100);
}
}
三、
// 地址选择默认值处理
if (this.form.provinceCode) {
console.log('走 4', provinceCode + cityCode + areaCode)
this.getProvinceFunc(provinceCode, cityCode, areaCode);
}
四、
// 初始默认赋值 - 省市区
getProvinceFunc(lable, cityCode, areaCode) {
// 请求省
let data = {
type: 1
};
let provinceList = '';
getArea(data).then(res => {
provinceList = res.data;
// 请求市
let data = {
provinceName: lable,
type: 2
};
let provinceIndex = '';
provinceList.forEach((el, index) => {
if (el.label === lable) {
provinceIndex = index;
}
});
getArea(data).then(res => {
provinceList[provinceIndex].children = res.data;
let data = {
provinceName: lable,
code: cityCode,
type: 3
};
let cityIndex = '';
provinceList[provinceIndex].children.forEach((el, index) => {
if (el.label === cityCode) {
cityIndex = index;
}
});
// 请求区
getArea(data).then(res => {
res.data.forEach(el => {
el.leaf = true; //回显必填
});
provinceList[provinceIndex].children[cityIndex].children = res
.data; //某个市children
this.options = provinceList;
// 设置值
initProvinceCode = lable; //设置默认的省
this.selectedOptions = [lable, cityCode, areaCode];
});
});
});
},
handleChooseAddressChange(value) {
console.log('value', value);
this.form.provinceCode = value[0];
this.form.cityCode = value[1];
this.form.areaCode = value[2];
}