本文主要是介绍使用vue3+elementplus的级联选择器实现省市区联动(三级到五级),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
中华人民共和国行政区划代码
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 = dataconst 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 = undefinedfor (let i = 0; i < data.length; i++) {if (parent) return parentlet 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 = dataoptions.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>
这篇关于使用vue3+elementplus的级联选择器实现省市区联动(三级到五级)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!