I'm using html and laravel to build select box options in a foreach loop
This works and populates with ID as value and name as the option. What I want, and can't quite figure out here, is how to take my function when I call it and get the id and value as separate vue options for a post axios call I'm going to make.
So when I select the option and submit the form to call the function, how can I get the ID as one prop and the name as another?
<select>
@foreach($details as $detail)
<option value="{{$detail->id}}">{{$detail->name}}</option>
@endforeach
</select>
new Vue({
data: {
detailID: [''],
detailName: ['']
},
methods: {
let data = {
detailID: this.detailID,
detailName: this.detailName
};
}
})
Here is a code example just using vue.js
Template
<div id="app">
<select v-model="selectedDetailId">
<option v-for="detail in details" v-bind:value="detail.id">
{{ detail.name }}
</option>
</select>
</div>
Script
new Vue({
el: '#app',
data: {
selectedDetailId: null,
details: [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
},
methods:{
post(){
//your selected Id is this.selectedDetailId
}
}
})
You can find more details and examples in the official Vue.js docs. https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings
Use v-model
to bind the selection to your component data. See Form input bindings
:
new Vue({ data: { detailID: "" }, // now you can access the id with this.detailID in your post request })
<select v-model="detailID"> @foreach($details as $detail) <option value="{{$detail->id}}">{{$detail->name}}</option> @endforeach </select>
And if you need both id
and name
, one work around could be:
new Vue({ data: { detail: "" }, // now you can access the id & name with this.detail.split(',') in your post request })
<select v-model="detail"> @foreach($details as $detail) <option value="{{$detail->id.','.$detail->name}}">{{$detail->name}}</option> @endforeach </select>
You would need to set a v-model to your select
element and bind the entire object to each option
element instead of just the id like you are doing in your example. Here is a codepen with a simple example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.