小颖公司最近作的项目用的vue+iviewui+axios,在作项目的过程当中,遇到一个问题:vue
二级联动的下拉框,第一个下拉框一直都有值,第二个下拉框是在选择了第一个下拉框以后采起调用ajax获取其值,但当点击重置按钮时,全部的查询条件都要置空,因此这时第二个下拉框的 option 的值也应是空的,但事实是虽然小颖在点击重置按钮时把第二个下拉框的option绑定的值置空了,但它仍是能获取到数据,最后定位到问题:
获取第二个下拉框的值是给第一个下拉框绑定的 on-change 中获取的,因此当先选择了第一个下拉框的值,再获取到第二个下拉框的值,此时再点击重置按钮时,已经触发了第一个下拉框的change事件。最后的解决方法是在on-change中先判断当前第一个下拉框是否有值,有值再去调ajax获取第二个下拉框的值。ios
<template> <Select v-model="whereMap.model1" style="width:200px" @on-change="getCityList2Fun"> <Option v-for="item in cityList1" :value="item.value" :key="item.value">{{ item.label }}</Option> </Select> <Select v-model="whereMap.model2" style="width:200px"> <Option v-for="item in cityList2" :value="item.value" :key="item.value">{{ item.label }}</Option> </Select> <Button class="search-btn" type="default" @click="searchClear">清空</Button> </template> <script> export default { data () { return { cityList1: [ { value: 'New York', label: 'New York' }, { value: 'London', label: 'London' }, { value: 'Sydney', label: 'Sydney' }, { value: 'Ottawa', label: 'Ottawa' }, { value: 'Paris', label: 'Paris' }, { value: 'Canberra', label: 'Canberra' } ], cityList2:[], whereMap:{ model1: '', model2: '', } } }, methods: { getCityList2Fun(){ this.cityList2=[ { value: 'New York', label: 'New York' }, { value: 'London', label: 'London' }, { value: 'Sydney', label: 'Sydney' }, { value: 'Ottawa', label: 'Ottawa' }, { value: 'Paris', label: 'Paris' }, { value: 'Canberra', label: 'Canberra' } ] }, searchClear() { this.whereMap={}; this.cityList2=[]; } } } </script>
其实就是修改 getCityList2Fun 方法ajax
getCityList2Fun() { if (this.whereMap.model1) { this.cityList2 = [ { value: 'New York', label: 'New York' }, { value: 'London', label: 'London' }, { value: 'Sydney', label: 'Sydney' }, { value: 'Ottawa', label: 'Ottawa' }, { value: 'Paris', label: 'Paris' }, { value: 'Canberra', label: 'Canberra' } ] } }