Vue2实现下拉框联动
常见的联动就是省份城市区县,下面例子主要是使用watch来实现,当一个输入框改变时,修改对应的级联的选项。
<template>
<div id="app">
<el-form :inline="true" :model="queryForm" class="demo-form-inline">
<el-form-item label="省份">
<el-select v-model="queryForm.province" clearable>
<el-option
v-for="item in provinceOpts"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="城市">
<el-select v-model="queryForm.city" clearable>
<el-option
v-for="item in cityOpts"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="区县">
<el-select v-model="queryForm.district" clearable>
<el-option
v-for="item in districtOpts"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="query">查询</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
queryForm: {},
provinceOpts: [],
cityOpts: [],
districtOpts: []
}
},
watch: {
'queryForm.province': function (newValue) {
this.selectChange('province', newValue)
},
'queryForm.city': function (newValue) {
this.selectChange('city', newValue)
}
},
created() {
this.getProvinceList()
},
methods: {
getProvinceList() {
// 初始化省份列表
this.provinceOpts = [{label:'广东',value:'001'},{label:'湖北',value:'002'},{label:'湖南',value:'003'}]
},
query() {
// 调用查询接口 传queryForm
console.log(this.queryForm)
},
selectChange(code, value) {
if (code === 'province') {
// 使用value值调用接口获取cityList值
// 假设有以下cityList
let cityListGD = [{label:'深圳市',value:'1101'},{label:'广州市',value:'1102'}]
let cityListHB = [{label:'武汉市',value:'1201'},{label:'荆州市',value:'1202'}]
let cityListHN = [{label:'长沙市',value:'1301'},{label:'湘潭市',value:'1302'}]
if (value === '001') {
this.cityOpts = cityListGD
} else if (value === '002') {
this.cityOpts = cityListHB
} else if (value === '003') {
this.cityOpts = cityListHN
} else {
this.cityOpts = []
}
// 当省份变化时,需要清空 城市 和 区县 的值
delete this.queryForm['city']
delete this.queryForm['district']
} else if (code === 'city') {
let districtListSZ = [{label:'南山区',value:'1101-1'},{label:'福田区',value:'1101-2'}]
let districtListWH = [{label:'洪山区',value:'1201-1'},{label:'武昌区',value:'1201-2'}]
let districtListCS = [{label:'雨花区',value:'1301-1'},{label:'岳麓区',value:'1301-2'}]
if (value === '1101') {
this.districtOpts = districtListSZ
} else if (value === '1201') {
this.districtOpts = districtListWH
} else if (value === '1301') {
this.districtOpts = districtListCS
} else {
this.districtOpts = []
}
// 城市变化只用清空 区县的值
delete this.queryForm['district']
}
}
}
}
</script>
<style>
</style>