vue 中国省市区级联数据 三级联动
- 安装插件
npm install element-china-area-data@5.0.2 -S
当前版本以测试,可用。 - 组件中使用了
element-ui,
https://element.eleme.cn/#/zh-CN/component/installation
库 请注意安装。 - 插件文档
https://www.npmjs.com/package/element-china-area-data
- 先上图
- 在components文件夹下面新建 mpAreaSelect.vue
<template><el-cascader:options="options":disabled="disabled":placeholder="placeholder":value="selectedOptions"@change="handleChange":clearable="clearable"></el-cascader>
</template><script>
import {provinceAndCityDataPlus,regionData,TextToCode,CodeToText,
} from 'element-china-area-data'
export default {name: 'mpAreaSelect',computed: {selectedOptions() {let selected = this.selected.filter((item) => item != '' && item != null)let len = selected.lengthlet textArr = []switch (len) {case 1:if(TextToCode[selected[0]]){textArr.push(TextToCode[selected[0]].code)}else{textArr = []}breakcase 2:if(TextToCode[selected[0]]){textArr.push(TextToCode[selected[0]].code)}else{textArr = []}if(TextToCode[selected[0]] && TextToCode[selected[0]][selected[1]]){textArr.push(TextToCode[selected[0]][selected[1]].code)}else{textArr = []}breakcase 3:if(TextToCode[selected[0]]){textArr.push(TextToCode[selected[0]].code)}else{textArr = []}if(TextToCode[selected[0]] && TextToCode[selected[0]][selected[1]]){textArr.push(TextToCode[selected[0]][selected[1]].code)}else{textArr = []}if(TextToCode[selected[0]] && TextToCode[selected[0]][selected[1]] && TextToCode[selected[0]][selected[1]][selected[2]]){textArr.push(TextToCode[selected[0]][selected[1]][selected[2]].code)}else{textArr = []}breakdefault:break}return textArr},options() {switch (this.level) {case 2:return provinceAndCityDataPluscase 3:return regionDatadefault:return regionData}},},props: {selected: {type: Array,default: [],},disabled: {type: Boolean,default: false,},placeholder: {type: String,default: '',},level: {type: Number,default: 3,},clearable:{type: Boolean,default: false,}},methods: {handleChange(value) {console.log(TextToCode)console.log(CodeToText)console.log(provinceAndCityDataPlus)console.log(regionData)console.log(value)this.$emit('change',value.map((item) => CodeToText[item]),value)},},
}
</script><style>
</style>
- 组件的使用
<template><div><div><div>请选择地区:</div><mp-area-selectstyle="width: 400px":selected="selected"placeholder="请选择地区"@change="changeAddress"></mp-area-select><div>回显地区:</div><mp-area-selectstyle="width: 400px":selected="selectedView"></mp-area-select></div></div>
</template>
<script>
import MpAreaSelect from '@/components/mpAreaSelect';
export default {components:{MpAreaSelect},data() {return {selected:[],selectedView:[],};},mounted(){this.$nextTick(()=>{this.selectedView = ["北京市", "市辖区", "朝阳区"]})},methods: {changeAddress(arr,code) {console.log(arr,77777777)console.log(code,88888888)},},
};
</script>
- 搞定!组件以及示例可直接复制使用!
- 另外 省市区JSON数据串 已经放在博客顶部,可自行下载后,自定义组件。