vue + elementUI实现省市县三级联动的方法示例
(编辑:jimmy 日期: 2024/11/28 浏览:3 次 )
本文介绍了vue + elementUI实现省市县三级联动的方法示例,分享给大家,具体如下:
1、首先需要准备省市县json文件,网上有很多可以下载。项目中使用的city.json数据是这样的格式:
[ { "value": "110000", "label": "北京市", "children": [ { "value": "110000", "label": "北京市", "children": [ { "value": "110101", "label": "东城区" }, { "value": "110102", "label": "西城区" }, { "value": "110105", "label": "朝阳区" }, { "value": "110106", "label": "丰台区" }, { "value": "110107", "label": "石景山区" }, { "value": "110108", "label": "海淀区" }, { "value": "110109", "label": "门头沟区" }, { "value": "110111", "label": "房山区" }, { "value": "110112", "label": "通州区" }, { "value": "110113", "label": "顺义区" }, { "value": "110114", "label": "昌平区" }, { "value": "110115", "label": "大兴区" }, { "value": "110116", "label": "怀柔区" }, { "value": "110117", "label": "平谷区" }, { "value": "110118", "label": "密云区" }, { "value": "110119", "label": "延庆区" } ] } ] }, { "value": "120000", "label": "天津市", "children": [ { "value": "120000", "label": "天津市", "children": [ { "value": "120101", "label": "和平区" }, ......
2、创建一个组件开始写代码
<template> <div class="linkage"> <div> <el-select v-model="selectProvince" filterable size="small" @change="selectProvinceFun($event)" placeholder="请选择省份"> <el-option value="" label="请选择省份"></el-option> <el-option :value="item" :label="item.label" v-for="(item, index) in city" :key="index"></el-option> </el-select> </div> <div> <el-select v-model="selectCity" filterable size="small" @change="selectCityFun($event)" placeholder="请选择城市"> <el-option value="" label="请选择城市"></el-option> <el-option :value="item" :label="item.label" v-for="(item, index) in cityList" :key="index"></el-option> </el-select> </div> <div> <el-select v-model="selectArea" filterable size="small" @change="selectAreaFun($event)" placeholder="请选择区县"> <el-option value="" label="请选择区县"></el-option> <el-option :value="item" :label="item.label" v-for="(item, index) in areaList" :key="index"></el-option> </el-select> </div> </div> </template> <script> import city from '@/assets/json/city.json' export default { name: 'linkage', data () { return { // 整个省市县数据 city: city, // 被选中的市数据 cityList: [], // 被选中的县数据 areaList: [], selectProvince: {}, selectCity: {}, selectArea: {} } }, mounted () { }, methods: { // 省份 市 县联动 selectProvinceFun (event) { console.log(event) if (event) { this.cityList = event.children } else { this.cityList = [] } this.areaList = [] this.$emit('getLawyerListInfo', [event.label, 'province']) }, selectCityFun (event) { console.log(event) if (event) { this.areaList = event.children } else { this.areaList = [] } this.$emit('getLawyerListInfo', [event.label, 'city']) }, selectAreaFun (event) { console.log(event) this.$emit('getLawyerListInfo', [event.label, 'area']) } } } </script> <style lang="scss" scoped> .linkage { display: flex; div { margin-right: 5px; } } </style>
总结:整个过程很简单,就是在选中省的时候获取他的所有children节点数据(市)在选择市的时候获取她的所有children节点数据(区县)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:vue 强制组件重新渲染(重置)的两种方案