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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With