3

new Vue({
    el: '#app',
    
    data: function() {
        return {
            countries: [],
            cities: [],
            selectedContinent: "",
            selectedCountry: "",
            selectedCity: ""
        }
    },
    watch: {
        selectedContinent: function() {
            // Clear previously selected values
            this.countries = [];
            this.cities = [];
            this.selectedCountry = "";
            this.selectedCity = "";
            // Populate list of countries in the second dropdown
            if (this.selectedContinent.length > 0) {
                this.countries = this.places[this.selectedContinent]
            }
        },
        selectedCountry: function() {
            // Clear previously selected values
            this.cities = [];
            this.selectedCity = "";
            // Now we have a continent and country. Populate list of cities in the third dropdown
            if (this.selectedCountry.length > 0) {
                this.cities = this.places[this.selectedContinent][this.selectedCountry]
            }
        }
    }
})
.dropdown {
    margin: 10px 0;
    padding: 10px 0;
    border-bottom: 1px solid #DDD;
}

.dropdown span {
    display:inline-block;
    width: 80px;
}
<body>
    <div id="app">
       <div class="cascading-dropdown">
            <div class="dropdown">
                <span>Continent:</span>
                <select v-model="selectedContinent">
                    <option value="">Select a Continent</option>
                    <option v-for="(country_obj, country) in places" :value="country">{{country}}</option>
                </select>
            </div>
            <div class="dropdown">
                <span>Country:</span>
                <select :disabled="countries.length == 0" v-model="selectedCountry">
                    <option value="">Select a Country</option>
                    <option v-for="(city_obj, city) in countries">{{city}}</option>
                </select>
            </div>
            <div class="dropdown"> 
                <span>City:</span>
                <select :disabled="cities.length == 0" v-model="selectedCity">
                    <option value="">Select a City</option>
                    <option v-for="city in cities">{{city}}</option>
                </select>
            </div>
        </div>
    </div> 
</body> 

Below is the REST API for countries, states and cities https://www.universal-tutorial.com/rest-apis/free-rest-api-for-country-state-city and I have generated a token. Generated Token : IIPwMXygilaKrQJfNLuj-LHZWn5kxBVZRLJ-KtU5jxRivdTBkHio6IOyF60CERyOPjo

Working codesandbox link:- https://jsfiddle.net/Dhanunjay/sj24kn0b/6/

With the list of items in data, i am able to load data in dropdown. But i am not sure how to load data using rest api in dropdown

Followed this documentation for Free REST API for countries, states and cities

4
  • It depends a bit how you want to use it. If you want to show data from the API response in the dropdown then you should make the api call in the mounted lifecycle hook and assign the response.data to a predefined item in data and loop through it in the template. You probably need to format the response though. If you want to show the data on each dropdown change then turn it into a function and call it each time a new item gets selected. Commented Oct 8, 2021 at 6:29
  • @uke5tar I tried the below code jsfiddle.net/Dhanunjay/sj24kn0b/5 I looped data in the template. But i am not sure how to assign the response to the dropdown. Can you please help me on how to place response in dropdown. Commented Oct 8, 2021 at 6:38
  • @uke5tar I updated my code as you said. But response how to load in dropdown not aware. Commented Oct 8, 2021 at 6:43
  • 1
    Do you mean like this: codesandbox.io/s/… ? Commented Oct 8, 2021 at 6:49

1 Answer 1

1

Step 1: Create HTML your template

<template>
  <div class="cascading-dropdown">
    <div class="dropdown">
      <H2>Build a reusable dropdown vue component</H2>
      <span>Country:</span>
      <select v-model="selectedCountry" @change="onChangeCountry">
        <option value="">Select a Country</option>
        <option
          v-for="(country, index) in listCountry"
          :value="country.country_name"
          :key="index"
        >
          {{ country.country_name }}
        </option>
      </select>
    </div>
    <div class="dropdown">
      <span>State:</span>
      <select
        :disabled="listState.length == 0"
        v-model="selectedState"
        @change="onChangeState"
      >
        <option value="">Select a State</option>
        <option
          v-for="(state, index) in listState"
          :key="index"
          :value="state.state_name"
        >
          {{ state.state_name }}
        </option>
      </select>
    </div>
    <div class="dropdown">
      <span>State:</span>
      <select :disabled="listCities.length == 0" v-model="selectedCity">
        <option value="">Select a City</option>
        <option
          v-for="(city, index) in listCities"
          :key="index"
          :value="city.city_name"
        >
          {{ city.city_name }}
        </option>
      </select>
    </div>
    <p v-if="selectedCountry">Selected Country - {{ this.selectedCountry }}</p>
    <p v-if="selectedState">Selected State - {{ this.selectedState }}</p>
    <p v-if="selectedCity">Selected City - {{ this.selectedCity }}</p>
  </div>
</template>

Step 2: Create model data

data() {
  return {
    listCountry: [],
    listState: [],
    listCities: [],
    selectedCountry: "",
    selectedState: "",
    selectedCity: "",
    authToken: "",
  };
},

Step 3: For getting Free REST API for countries, states and cities. We needs to generate auth_token from api-token

generateAccessToken() {
  axios
    .get("https://www.universal-tutorial.com/api/getaccesstoken", {
      headers: {
        Accept: "application/json",
        "api-token":
          "jAJuES2nNREYu0qOJ9Sy6bydr_LPxmjv0jUAR-oEuXozRP_CjqPqRgp1mCPaNh8VPZo",
        "user-email": "[email protected]",
      },
    })
    .then((res) => {
      this.authToken = res.data.auth_token;
      this.loadCountry();
    });
},

Step 4: Create onChange events for country, state and cities

loadCountry() {
  axios
    .get("https://www.universal-tutorial.com/api/countries", {
      headers: {
        Authorization: `Bearer ${this.authToken}`,
        Accept: "application/json",
      },
    })
    .then((res) => {
      this.listCountry = res.data;
    });
},
onChangeCountry() {
  axios
    .get(
      `https://www.universal-tutorial.com/api/states/${this.selectedCountry}`,
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`,
          Accept: "application/json",
        },
      }
    )
    .then((res) => {
      this.listState = res.data;
    });
},
onChangeState() {
  axios
    .get(
      `https://www.universal-tutorial.com/api/cities/${this.selectedState}`,
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`,
          Accept: "application/json",
        },
      }
    )
    .then((res) => {
      this.listCities = res.data;
    });
},

DEMO

Sign up to request clarification or add additional context in comments.

Comments

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.