Vue------实现省市区三级联动
时间: 2023-10-08 11:12:46 浏览: 194
Vue实现省市区三级联动的代码如下:
```html
<body>
<div id="app">
<div>
<span>省</span>
<select v-model="pro">
<option :value="p.adcode" v-for="p in list">{{p.name}}</option>
</select>
<span>市</span>
<select v-model="city">
<option :value="item.adcode" v-for="(item,index) in list.find(c=>c.adcode==pro).districts">{{item.name}}</option>
</select>
<span>区</span>
<select v-model="county">
<option :value="item.adcode" v-for="(item,index) in list.find(c=>c.adcode==pro).districts.find(x=>x.adcode==city).districts">{{item.name}}</option>
</select>
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
pro: "110000",
city: "",
county: "",
list: citys
},
methods: {
loadCity(proCode) {
let $citys = this.list.find(s => s.adcode == proCode).districts[0];
if ($citys != null) {
this.city = $citys.adcode;
}
},
loadCounty(proCode, cityCode) {
let $county = this.list.find(s => s.adcode == proCode).districts.find(x => x.adcode == cityCode).districts[0];
if ($county != null) {
this.county = $county.adcode;
}
}
},
created() {
this.loadCity(this.pro);
this.loadCounty(this.pro, this.city);
},
watch: {
pro: function (newVal, oldVal) {
this.loadCity(newVal);
},
city: function (newVal, oldVal) {
this.loadCounty(this.pro, this.city);
}
},
})
</script>
</body>
```
以上代码实现了一个省市区三级联动的功能。通过Vue的v-model指令将省、市、区的选择值与数据绑定,通过监听数据的变化,动态更新市、区的选项列表。
阅读全文