How do I always select the first item with a select (in vue.js)?
<div class="ride-item-content">
<select v-model="ride.location_id">
<option v-for="location in locations" v-bind:value="location.id">
{{ location.from }} - {{ location.to }}
</option>
</select>
</div>
json
{
"locations": {
"total": 2,
"per_page": 20,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 1,
"user_id": 1,
"description": "sdg",
"from": "asdf",
"to": "asdf",
"kmz": "12",
"kmp": "13",
"time": 0,
"hour": 0,
"maps": "www.blablabla.nl",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"user_id": 1,
"description": "asdf",
"from": "asdf",
"to": "asdf",
"kmz": "3",
"kmp": "1",
"time": 1,
"hour": 0,
"maps": "www.test.nl",
"created_at": null,
"updated_at": null
}
]
}
}
--EDIT--
<div class="ride-item-content">
<select v-model="ride.location_id">
<option v-for="location in locations" v-bind:selected="$index === 0 ? 'selected' : false">
{{ location.from }} - {{ location.to }}
</option>
</select>
</div>
VueJS 1:
<option v-for="location in locations" v-bind:value="location.id" v-bind:selected="$index === 0 ? 'selected' : false">
{{ location.from }} - {{ location.to }}
</option>
VueJS 2:
<option v-for="(location, index) in locations" v-bind:value="location.id" v-bind:selected="index === 0">
{{ location.from }} - {{ location.to }}
</option>
In Vue 1, $index
is automatically available inside v-for
loops.
In Vue 2, you need to explicitly declare a variable for the index.
In your json I cant find location.id
. And your "locations"
is obj. But if the "locations"
is arr, you can use this:
<select v-model="selectedLocation">
<option v-for="location in locations" :key="location.id" :value=location.id>
{{ location.somekey }}
</option>
</select>
in data -
selectedLocation: this.locations.length ? this.locations[0].id : ''
It can work because your select depends on selectedLocation (v-model)
.
You can use v-model in your select , when you load your list pass first value to a model variable and always first value will be selected
created(){
if(this.locations) {
this.ride.location_id = this.locations[0].id
}
}
working example jsfidlle link https://jsfiddle.net/Rashid_Bukhari/q2ro6pz1/20/
you just need to update your v-model ride.location_id
into vuejs created(){}
or mounted(){}
method
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