如何在vuejs中的下拉选择中处理多个on change事件

时间:2017-08-19 18:50:08

标签: javascript vue.js vuejs2

我遇到一个问题,用户需要首先选择国家/地区,然后选择州和城市。现在我在国家和州设置了@change事件,一旦用户选择了国家,它就会获取状态,同时也会触发@change on states,因为我有state_id ='',现在我的getCities函数失败了。

<select v-model="country_id" @change="getStates()">
    <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>
<select v-model="state_id" @change="getCities()">
    <option v-for="state in states" :value="state.id">{{ state.name }}</option>
</select>

data(){
    return{
        countries: [],
        states: [],
        cities: [],
        country_id: '',
        state_id: '',
        city_id: ''
    }
},
mounted(){
    getCountries();
},
methods:{
    getCountries(){
        // this.countries = response.data
    }
    geStates(){
        //get states where country_id = this.country_id
    },
    getCities(){
        //get cities where state_id = this.state_id
        //once country is selected even this is getting triggered
    }

}

1 个答案:

答案 0 :(得分:1)

在实际获取数据之前,只需检查状态是否有值。

getCities(){
    // Check to see if state_id has a value
    if (!this.state_id) return

    //get cities where state_id = this.state_id
    //once country is selected even this is getting triggered
}