作者是前端小白,最近项目里用到了城市级联菜单,框架用的vue+iview,封装了一下city组件,给大家分享一下,不喜勿喷。
组件 city.vue
<template>
<div class="city_box">
<Select v-model="province_value" style="width:200px" @on-change="changeProvince">
<Option v-for="item in provinceList" :value="item.value" :key="item.value">{{ item.label }}</Option>
</Select>
<Select v-model="city_value" style="width:200px" @on-change="changeCity" >
<Option v-for="item in curCity" :value="item.value" :key="item.value">{{ item.label }}</Option>
</Select>
<Select v-model="county_value" style="width:200px" >
<Option v-for="item in curCounty" :value="item.value" :key="item.value">{{ item.label }}</Option>
</Select>
</div>
</template>
<script>
export default {
data() {
return {
curCity: [],
curCounty: [],
province_value: "all",
provinceList: [
{
value: "all",
label: "所有省份"
}
],
city_value: "all",
cityList: {
all: []
},
county_value: "all",
countyList: {
all: []
},
citys: null
};
},
methods: {
changeProvince() {
this.curCity = this.cityList[this.province_value];
this.county_value = "";
this.city_value = "";
},
changeCity() {
this.curCounty = this.countyList[this.city_value];
this.county_value = "";
}
},
mounted() {},
created() {
//城市级联菜单接口
this.$http({
url:
"https://www.easy-mock.com/mock/5d5c92b5dbbe62287bcf6824/mock/cityList",
method: "get"
}).then(res => {
this.citys = res.data.data;
for (var i of this.citys) {
this.provinceList.push({ value: i.name, label: i.name });
this.cityList[i["name"]] = [];
this.cityList[i["name"]][0] = { value: "all", label: "所有城市" }
for (var k of i["cityList"]) {
if(i["name"] == '北京'||i["name"] == '天津'||i["name"] == '上海'||i["name"] == '重庆'){ //直辖市清除所有城市选项
this.cityList[i["name"]].length = 0 ;
}
this.cityList[i["name"]].push({ value: k["name"], label: k["name"] });
this.countyList[k["name"]] = [];
this.countyList[k["name"]][0] = { value: "all", label: "所有区县" }
for (var j of k["areaList"]) {
this.countyList[k["name"]].push({value: j["name"], label: j["name"]});
}
}
}
});
}
};
</script>
然后在main.js里注册一下city组件,就可以使用了
main.js
import CityList from '@/components/cityList'
Vue.component('CityList', CityList);
使用:
通过this.$refs.city可以拿到对应的值
this.$refs.city.province_value 当前省份
this.$refs.city.city_value 当前城市
this.$refs.city.county_value=>当前区县
<!-- 这里是其他vue文件 -->
<CityList ref="city"></CityList>
效果图

城市级联菜单.png
对了,我不知道easy-mock的接口别人能不能调用,不能的话记得@我 = =...
就到这里了,拜拜