how to make dependent second list in vuejs using json raw data?

Viewed 43

so i have state and districts list stored in a .json file. I can bring the list of states in the first menu but unable to bring that selected states district list in second dropdown.

"locations":[  
 {  
    "state":"Andhra Pradesh",
    "districts":[  
       "Anantapur",
       "Chittoor",
       "East Godavari",
       "Guntur",
       "Krishna",
       "Kurnool",
       "Nellore",
       "Prakasam",
       "Srikakulam",
       "Visakhapatnam",
       "Vizianagaram",
       "West Godavari",
       "YSR Kadapa"
    ]
 },
 {  
    "state":"Arunachal Pradesh",
    "districts":[  
       "Tawang",
       "West Kameng",
       "East Kameng",
       "Papum Pare",
       ........

how do i bring the list of one particular district?

<b-form-input
                  list="my-list-id-2"
                  v-model="memorial.location1"
                  required
                  :placeholder="$t('placeholdersMemorial.location1')"
                ></b-form-input>
                <datalist id="my-list-id-2">
                  <option v-for="location in $t('locations')" :key="location">{{ location.state }}</option>
                </datalist>
              </b-form-group>
            </b-col>

above is my first box, which lists states.

 <b-row class="justify-content-center">
           <b-col cols="8" sm="8">
              <b-form-group
                :label="$t('addMemorialForm.location2')"
              >
                <b-form-input
                  list="my-list-id-2b"
                  v-model="memorial.location2"
                   v-if="memorial.location1"
                  required
                  :placeholder="$t('placeholdersMemorial.location2')"
                ></b-form-input>
                <datalist id="my-list-id-2b">
                  <option v-for="location in $t('locations')" :key="locations">{{ locations.districts }}</option>
                </datalist>
              </b-form-group>
            </b-col>

above is for secon box. how can i solve this?

1 Answers

In this case you could add the districts array as a computed property:

  computed: {
    availableDistricts () {
      if (this.memorial.location1) {
        const selectedState = this.$t('locations').find(loc => loc.state === this.memorial.location1);
        return selectedState.districts;
      } else {
        return [];
      }
    }
  },

And then use it like this:

   <datalist id="my-list-id-2b">
        <option v-for="district in availableDistricts" :key="district">{{district}}</option>
   </datalist>
Related