使用element-ui制作三级级联城市选择器

时间:2023-03-09 16:26:15
使用element-ui制作三级级联城市选择器

1.效果预览:

使用element-ui制作三级级联城市选择器

2.引入资源文件

1.vue资源

<script src="https://unpkg.com/vue/dist/vue.js"></script>

2.elementUI资源

<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

3.city-data.js资源

3.业务代码

1.html代码

<div id="app">
  <el-cascader :options="CityInfo" v-model="form.selectedOptions" :change-on-select="true" :clearable="true" :filterable="true" @change="handleChange">
  </el-cascader>
  <span>所选地区:{{form.city | myAddressCity}}{{form.area | myAddressArea}}{{form.minarea | myAddressMinarea}}</span>
</div>

2.js代码

     const app = new Vue({
el: '#app',
data: {
CityInfo: CityInfo,
form: {
city: '',
area: '',
minarea: '',
selectedOptions: [],//地区筛选数组
},
},
created() {
},
methods: {
handleChange(value) {
this.form.city = this.form.selectedOptions[0];
this.form.area = this.form.selectedOptions[1]
this.form.minarea = this.form.selectedOptions[2]
},
20    },
filters: {
myAddressCity: function (value) {
for (y in this.CityInfo) {
if (this.CityInfo[y].value == value) {
return value = this.CityInfo[y].label
}
}
},
myAddressArea: function (value) {
for (y in this.CityInfo) {
for (z in this.CityInfo[y].children) {
if (this.CityInfo[y].children[z].value == value && value != undefined) {
return value = this.CityInfo[y].children[z].label;
}
}
}
},
myAddressMinarea: function (value) {
for (y in this.CityInfo) {
for (z in this.CityInfo[y].children) {
for (i in this.CityInfo[y].children[z].children) {
if (this.CityInfo[y].children[z].children[i].value == value && value != undefined) {
return value = this.CityInfo[y].children[z].children[i].label
}
}
}
}
},
},
})

制作完成,其他更多用法参考官网:http://element-cn.eleme.io/#/zh-CN/component/cascader

后记1:在city-data.js中删除第三级地区,就可以实现省市二级联动.

    地址:https://github.com/Ele-Cat/Ele-Cat.github.io/blob/master/city-data-2d.js

后记2:用vuejs+elementUI写了一个可查看全国城市的天气预报功能,项目演示地址:https://ele-cat.github.io/forecast/,代码地址:https://github.com/Ele-Cat/Ele-Cat.github.io/tree/master/forecast