H5使用的vant,后管使用Element,两个组件所使用的的数据源不一样,导致两端的级联选择问题。
解决方案 :将vant的资源库处理为element需要的数据。
//vant的数据源
var areaList = {}
let regionData = [];
const areaFormat= () =>{
let _this = this,
cityNum = '',
countyNum = '';
for (let p in areaList.province_list) {
let province_option = {
value: p,
label: areaList.province_list[p],
children: [],
};
regionData.push(province_option);
}
for (let c in areaList.city_list) {
let city_option = {
value: c,
label: areaList.city_list[c],
children: [],
};
//城市与省会的索引差介于100到10000
regionData.map((item, index) => {
let diff = c - parseInt(item.value);
if (diff < 10000 && diff > 99 && index < 34) {
regionData[index].children.push(city_option);
}
//这里是外国数据
if (index > 33 && c > 900000) {
regionData[index].children.push({
value: c,
label: areaList.city_list[c],
});
}
});
}
//城市与城区的索引差小于100
for (let t in areaList.county_list) {
let county_option = {
value: t,
label: areaList.county_list[t],
};
regionData.map((item, index) => {
item.children.map((itemChild, indexChild) => {
let diff = t - parseInt(itemChild.value);
if (diff > 0 && diff < 100) {
regionData[index].children[indexChild].children.push(county_option);
}
});
});
}
};
areaFormat()
export default areaFormat;
h5选择地址后存为两个字段:birthProv, birthCity
因为element选择完地址后返回的地址格式为一个数组:结构类似于 ['110000','110001','110002']
,而且数据库存的值为一个中文字符
所以还需要封装两个函数来转换code和地址中文。
import regionData from './area-data';
import { ref } from 'vue';
const Code2Area = (curAreaList: string[]) => {
const province = curAreaList[0];
const city = curAreaList[1];
const county = curAreaList[2];
//获取到省份的总体数据
const res_province = regionData.filter((val) => val.value == province);
console.log(res_province);
//在省份里递归找到市
const res_city = res_province[0].children.filter((val) => val.value == city);
//在市里面递归找到区、县
const res_county = res_city[0].children.filter((val) => val.value == county);
return {
province: res_province[0]?.label,
city: res_city[0]?.label,
county: res_county[0]?.label,
};
};
const Area2Code = (province: string, city: string, county: string) => {
console.log(province, city, county);
if (province && city && county) {
//获取到省份的总体数据
const res_province = regionData.filter((val) => val.label == province);
console.log(res_province);
//在省份里递归找到市
const res_city = res_province[0].children.filter((val) => val.label == city);
console.log(res_city);
//在市里面递归找到区、县
const res_county = res_city[0].children.filter((val) => val.label == county);
return [res_province[0]?.value, res_city[0]?.value, res_county[0]?.value];
}
};
export const computeArea = () => {
return { Code2Area, Area2Code};
};
现在就可以实现h5和后管同时起作用了!
h5选择地址后的值
const data={
birthProv:'上海市',
birthCity:'上海市-普陀区'
}
候选回显:
const birthArea=ref()
if (data.birthCity) {
birthArea.value = Area2Code(data.birthProv, data.birthCity.split('-')[0], data.birthCity.split('-')[1]);
}
<el-cascader
@change="changeB"
v-model="birthArea"
:options="regionData"
separator="-"
placeholder="请选择"
:props="{multiple: false}"
clearable>
el-cascader>
参考:
参考地址