0

I have a problem where user needs to select countries first and then states and then cities. Now I have setup @change event on countries and states, as soon as the user selects country it fetches states and also @change on states is also triggered, and since I have state_id = '', now my getCities function fails.

<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 Answer 1

2

Just check to see if the state has a value before actually getting the data.

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I did this. But wanted to know if vuejs has an event for on selected.
@JagadeshaNH change is basically on selected. In this case, Vue is just using native methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.