Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate select tag with data from API in Vue and Axios

Tags:

laravel

vue.js

I want to populate select tag with data from api get request. Here is my html code

<div id="app">
    <label for="country" class="control-label">Country</label>
    <select v-model="selectedCountry" @change="onChangeCountry" name="country" id="country" class="form-control" tabindex="11">
        <option selected disabled value="">Please select one</option>
        @foreach($countries as $country)
            <option value="{{ $country->id }}">{{ $country->name }}</option>
        @endforeach
    </select>
    <label for="city" class="control-label">City</label>
    <select v-model="cities" name="city" id="city" class="form-control" tabindex="12">
        <option v-bind:value="city.id">@{{ city.name }}</option>
    </select>
</div>

And now my JavaScript code:

<script type="text/javascript">
    new Vue({
      el: '#app',
      data: {
        selectedCountry: '',
        cities: []
      },
      methods: {
          onChangeCountry: function (event) {
            axios.get('http://localhost:8000/api/cities/country/' + this.selectedCountry)
            .then(function (
                this.cities = response.data
            }).catch(function(error) {
                console.log('an error occured ' + error);
            });
          }
        }
    });
</script>

I'm pretty sure that the data is received because i did a lot of console.log but I don't know how to append the received data to my second select tag nor how to proceed.

like image 766
Wajdi Makhlouf Avatar asked Mar 02 '18 09:03

Wajdi Makhlouf


2 Answers

Try this in the select

<select v-model="selectedCity" name="city" id="city" class="form-control" tabindex="12">

   <option v-for="(city,cityIndex) in cities" :key="city.id" :value="city.id">{{ city.name }}</option>

</select>

Add 'selectedCity' to the data object and then access its value through this.selectedCity

This is in the vue docs

https://v2.vuejs.org/v2/guide/list.html

https://v2.vuejs.org/v2/guide/forms.html#Select

like image 111
Sérgio Reis Avatar answered Nov 15 '22 05:11

Sérgio Reis


I finally got it working
i just needed to create a city variable in data function
and in select i don't need to bind it to array of cities[], the city variable is fine v-model="city"

like image 44
Wajdi Makhlouf Avatar answered Nov 15 '22 06:11

Wajdi Makhlouf