vue将地区以对象、数组的格式传给后端
项目涉及到了一个地区筛选,同时省市区三级不进行关联,后端要求以对象包数组的格式传参,完整代码
1、先拿到接口返回的地区数据

对数据进行处理,拿到想要的格式
this.provinceOption =res.data.map((item) => {
let name = '';
if (item.name.includes('内蒙古') || item.name.includes('黑龙江')) {
name = item.name.slice(0, 3);
} else {
name = item.name;
}
return {
...item,
name,
};
});
2、vue用element级联选择器插件渲染
<el-cascader v-model="search.area" placeholder="请选择" @change="areaChange" @visible-change="enpVisibleChange"
:options="provinceOption" filterable clearable collapse-tags :props="{
multiple: true,
checkStrictly: true,
label: 'name',
value: 'name',
expandTrigger: 'hover',
children: 'nextLevel',
}" size="midium">
</el-cascader>
重点来了,将插件返回的数据进行处理
思路:先将每个数组的第一项存起来,将他们转为对象的key,然后再将数组的第二项作为对象中的key,第三项存到对应的数组中

3、将选中的地区返回的数据进行处理,改成接口需要的参数格式

areaChange() {
const countryArray = [];
const countryList = {}
this.search.area.forEach(item => {
if (!countryArray.includes(item[0])) {
countryArray.push(item[0])
}
})
if (countryArray.length > 0) {
countryArray.forEach(item => {
countryList[item] = {}
if (item.includes('市')) {
countryList[item][item] = []
}
this.search.area.forEach(areaItem => {
if (areaItem.length === 2 && areaItem[0].includes('市')) {
if (item === areaItem[0]) {
areaItem.forEach(areaItemChild => {
if (item !== areaItemChild && !countryList[item][item].includes(areaItemChild)) {
countryList[item][item].push(areaItemChild)
}
})
}
} else if (areaItem.length >= 2 && item === areaItem[0]) {
if (!countryList[item][areaItem[1]]) {
countryList[item][areaItem[1]] = []
}
areaItem.forEach(areaItemChild => {
if (item !== areaItemChild && !countryList[item][areaItem[1]].includes(areaItemChild) && areaItem[1] !== areaItemChild) {
countryList[item][areaItem[1]].push(areaItemChild)
}
})
}
})
})
}
this.search.countryList = countryList;
if (!this.enpVisible) {
this.policySearchList();
}
},
以上就是完整的代码和步骤

浙公网安备 33010602011771号