通过一个 citycode 比如
结果:
以下是封装的代码
//area.js
import { findAllParents } from "@/utils/json";
export function getAreaCode(nodeId) {
const parents = findAllParents(getArea(),{"code":nodeId},(item,node) => item.code === node.code,{
props: {
children: "child"
}
});
let codes = []
let names = []
for(let node of parents) {
codes.push(node.code)
names.push(node.name)
}
codes.push(nodeId)
let data = {codes:codes,names:names}
return data
}
//省市县 三级
//这个json我在网上找的 太长了不复制那么多
export function getArea (){
let data = [
{"code":"110000","name":"北京市","child":[{"code":"110100","name":"北京城区","child":[{"code":"110106","name":"丰台区","child":null},{"code":"110107","name":"石景山区","child":null},{"code":"110108","name":"海淀区","child":null},{"code":"110109","name":"门头沟区","child":null},{"code":"110111","name":"房山区","child":null},{"code":"110112","name":"通州区","child":null},{"code":"110113","name":"顺义区","child":null},{"code":"110114","name":"昌平区","child":null},{"code":"110115","name":"大兴区","child":null},{"code":"110116","name":"怀柔区","child":null},{"code":"110117","name":"平谷区","child":null},.......]
return data
}
//json.js
const defaults = {
props: {
children: "children"
}
}
export const findParent = (data, node, predicate, options = {}) => {
let config = Object.assign({}, defaults, options);
let parent = undefined;
for (let i = 0; i < data.length; i++) {
if (parent)
return parent;
let item = data[i];
if (item[config.props.children] && item[config.props.children].length > 0) {
let child = item[config.props.children].filter(c => predicate(c, node));
if (child.length > 0) {
parent = item;
}
if (parent === undefined) {
parent = findParent(item[config.props.children], node, predicate, config);
} else {
break;
}
}
}
return parent;
}
export const findAllParents = (data, node, predicate, options = {}) => {
let config = Object.assign({}, defaults, options);
let allParents = [];
let parent = findParent(data, node, predicate, config);
while (parent !== undefined) {
allParents.unshift(parent);
parent = findParent(data, parent, predicate, config);
}
return allParents;
}
over~~