vue+iview实现省市二级联动
时间: 2023-12-16 20:03:33 浏览: 198
1. 首先,在项目中引入iview和vue-resource:
```
import Vue from 'vue'
import iView from 'iview'
import 'iview/dist/styles/iview.css'
import VueResource from 'vue-resource'
Vue.use(iView)
Vue.use(VueResource)
```
2. 在vue文件中使用iview的Select组件实现省市选择:
```
<template>
<div>
<Select v-model="province" @on-change="getCityList">
<Option v-for="(item, index) in provinceList" :value="item.id" :key="index">{{ item.name }}</Option>
</Select>
<Select v-model="city">
<Option v-for="(item, index) in cityList" :value="item.id" :key="index">{{ item.name }}</Option>
</Select>
</div>
</template>
<script>
export default {
data () {
return {
province: '',
city: '',
provinceList: [],
cityList: []
}
},
mounted () {
this.getProvinceList()
},
methods: {
// 获取省份列表
getProvinceList () {
this.$http.get('/api/province').then(res => {
this.provinceList = res.data
})
},
// 获取城市列表
getCityList () {
this.$http.get('/api/city', {
params: {
province: this.province
}
}).then(res => {
this.cityList = res.data
})
}
}
}
</script>
```
3. 在后台实现省市数据接口:
省份接口:
```
app.get('/api/province', function(req, res) {
res.json([
{id: 1, name: '北京'},
{id: 2, name: '上海'},
{id: 3, name: '广东省'},
{id: 4, name: '湖南省'}
])
})
```
城市接口:
```
app.get('/api/city', function(req, res) {
var provinceId = req.query.province
var cityList = []
switch(provinceId) {
case '1':
cityList = [
{id: 101, name: '北京市'},
{id: 102, name: '海淀区'},
{id: 103, name: '朝阳区'},
{id: 104, name: '东城区'},
{id: 105, name: '西城区'}
]
break
case '2':
cityList = [
{id: 201, name: '上海市'},
{id: 202, name: '浦东新区'},
{id: 203, name: '徐汇区'},
{id: 204, name: '黄浦区'},
{id: 205, name: '静安区'}
]
break
case '3':
cityList = [
{id: 301, name: '广州市'},
{id: 302, name: '深圳市'},
{id: 303, name: '珠海市'},
{id: 304, name: '佛山市'},
{id: 305, name: '东莞市'}
]
break
case '4':
cityList = [
{id: 401, name: '长沙市'},
{id: 402, name: '株洲市'},
{id: 403, name: '湘潭市'},
{id: 404, name: '衡阳市'},
{id: 405, name: '邵阳市'}
]
break
default:
break
}
res.json(cityList)
})
```
阅读全文