中华人民共和国行政区划代码
github地址:https://github.com/uiwjs/province-city-china
中华人民共和国行政区划(五级):省级、地级、县级、乡级和村级。来自中华人民共和国民政部,用于查询中国省,市和区数据的网站。
安装
npm install province-city-china --save-dev
使用
const { data, province, city, area, town } = require(‘province-city-china/data’);
代码实现
<template>
<div>
<el-cascader v-model="value" :options="options" @change="handleChange" />
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import data from 'province-city-china/dist/level.json'
const value = ref([])
const options = ref([])
const handleChange = (value) => {
console.log(value)
}
const dataList = data
const getAreaCode = (nodeId) => {
const parents = findAllParents(
dataList,
{ 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.js
const defaults = {
props: {
children: 'children'
}
}
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
}
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
}
onMounted(() => {
options.value = data
options.value = options.value.map((item) => {
return {
value: item.code,
label: item.name,
children: item.children?.map((item2) => {
return {
value: item2.code,
label: item2.name,
children: item2.children?.map((item3) => {
return {
value: item3.code,
label: item3.name
}
})
}
})
}
})
value.value = getAreaCode('420106').codes
})
</script>