ant design vue级联选择懒加载省市区三级数据
项目中原先是展示的一级数据,后面根据需求改成精确到县的。
使用Cascader级联选择,后台返回的是获取省份的字典接口,根据codeValue一级级查询进行动态加载。
<a-form-model-item prop="projectArea" ref="projectArea" :labelCol="{ span: 10 }" :wrapperCol="{ span: 12 }" label="项目部所在地:" > <a-tooltip> <template slot="title"> 项目部所在地 </template> <a-cascader :allowClear="false" :options="projectAreaOptions" v-model="form1.projectArea" placeholder="请选择区域" :loadData="loadAreaData" @change="onAreaChange" :getPopupContainer="(trigger) => {return trigger.parentElement}"> </a-cascader> </a-tooltip> </a-form-model-item>
async mounted() { this.getAppendTemplate(); const data = await this.getAreaList() || []; this.projectAreaOptions = data.map(item => { item.leaf = false; return item; }) }
//获取省份数据 getAreaList(code) { return new Promise((resolve, reject) => { code = -1; publicapi.findAllProvinceLazy(code).then(res => { if (res.options) { let arr = res.options.map(item => { return { value: item.id, label: item.label, isLeaf: item.leaf } }) return resolve(arr) } else { return resolve([]) } }).catch((err) => { return reject(err) }) }) }, //获取下一级数据 async loadAreaData(selectedOptions) { if (!this.projectAreaOptions.length) { this.projectAreaOptions = await this.getAreaList() || []; } else { const targetOption = selectedOptions[selectedOptions.length - 1]; targetOption.loading = true; const data = await publicapi.findAllProvinceLazy(targetOption.value); console.log(data, 'targetOption.value', targetOption.value); if (data.options.length) { for (let index = 0; index < data.options.length; index ++) { const element = data.options[index]; if (element.children) { delete element.children } element.value = element.id; element.isLeaf = false; } targetOption.loading = false; targetOption.children = [...data.options]; this.projectAreaOptions = JSON.parse( JSON.stringify(this.projectAreaOptions) ); } else { targetOption.loading = false; targetOption.isLeaf = true; } } }, //选择区域后的操作 onAreaChange(val, selectedOptions) { console.log(val, selectedOptions, 'val, selectedOptions') },
非懒加载的级联,后台一次性返回所有数据机构
<a-cascader :options="projectAreaOptions" v-model="form1.projectArea" placeholder="请选择区域" @change="onAreaChange" :field-names="{label: 'label', value: 'id', children: 'children'}" :getPopupContainer="(trigger) => {return trigger.parentElement}" />
使用fieldNames自定义options 中 label name children 的字段
后台返回的数据