如何选择带有select的第一个项目(在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
}
]
}
}
- 编辑 -
<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>
答案 0 :(得分:5)
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>
在Vue 1中,$index
圈内会自动提供v-for
。
在Vue 2中,您需要为索引显式声明一个变量。
答案 1 :(得分:1)
在您的json中,我找不到location.id
。而您的"locations"
是obj。但是,如果"locations"
是arr,则可以使用以下代码:
<select v-model="selectedLocation">
<option v-for="location in locations" :key="location.id" :value=location.id>
{{ location.somekey }}
</option>
</select>
数据中-
selectedLocation: this.locations.length ? this.locations[0].id : ''
它可以工作,因为您的选择取决于selectedLocation (v-model)
。
答案 2 :(得分:0)
与@J相似。布鲁尼的答案虽然对你来说似乎不起作用。试试这个:
<option v-for="location in locations" v-bind:value="location.id" v-bind:selected="$index === 0 ? true : false">
{{ location.from }} - {{ location.to }}
</option>
答案 3 :(得分:0)
您可以在select中使用v-model,当您加载列表时,将第一个值传递给模型变量,并且始终会选择第一个值
答案 4 :(得分:0)
created(){
if(this.locations) {
this.ride.location_id = this.locations[0].id
}
}
工作示例jsfidlle链接 https://jsfiddle.net/Rashid_Bukhari/q2ro6pz1/20/
您只需要将v模型ride.location_id
更新为vuejs created(){}
或mounted(){}
方法