实现一个省市区对应列表
2018-11-09 本文已影响26人
sweetBoy_9126
首先引入一个address.json文件,部分内容展示如下:
{
"list": [
{
"children": [
{
"children": [
{
"label": "东城区",
"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": 110100
}
],
"label": "北京市",
"value": 110000
}
]
}
在vue组件里引入address.json
<div class="select-group" v-if="addressData">
<select v-model.number="provinceValue">
<option value="-1">选择省份</option>
<option v-for="p in addressData" :value="p.value" :key="p.value">{{p.label}}</option>
</select>
<select v-model.number="cityValue">
<option value="-1">选择城市</option>
<option v-for="c in cityName" :value="c.value" :key="c.value">{{c.label}}</option>
</select>
<select v-model.number="districtValue">
<option value="-1">选择地区</option>
<option v-for="d in districtName" :value="d.value" :key="d.value">{{d.label}}</option>
</select>
</div>
<script>
import AddressData from 'js/address.json'
export default{
data(){
return {
provinceValue: -1,
cityValue: -1,
districtValue: -1,
address: '',
addressData: null,
cityName: null,
districtName: null
}
},
created(){
this.addressData = AddressData.list
},
watch: {
provinceValue(val){
if(val === -1) return
let list = this.addressData
// 找到provinceValue为你选中list中的当前val值的索引
let index = list.findIndex(item=>{
return item.value === val
})
//城市的数据就在当前索引值下的children
this.cityName = list[index].children
//每次选中后初始化市和区
this.cityValue = -1
this.districtValue = -1
},
cityValue(val){
if(val === -1) return
let list = this.cityName
// 找到cityName为你选中list中的当前val值的索引
let index = list.findIndex(item=>{
return item.value === val
})
this.districtName = list[index].children
//每次选中后初始化区
this.districtValue = -1
}
}
}
</script>