How can I pass index from option to v-model in select?
<select v-model="selectedItem">
<option v-for="item, index" in list" :index="index">{{item}}</option>
</select>
selectedItem
just store item, without index. How can I get the option index, like selectedItem.index
?
You can Bind the option
tag value to the index
:
<select v-model="selectedItem">
<option v-for="item, index" in list" :value="index">{{item}}</option>
</select>
The selectedItem
will then be the selected item's index, you don't need to have both the item and its index at the same time as it is redundant:
const item = this.list[this.selectedItem];
If you want the index to be stored on selectedItem.index
then you have to make the v-model
be selectedItem.index
Other than that you need to change :index
to :value
and fix your syntax issue with your v-for
new Vue({ el: '#app', data: { selectedItem: {}, list: [5, 6, 7, 8, 9] } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <select v-model="selectedItem.index"> <option v-for="(item, index) in list":value="index">{{item}}</option> </select> <pre>{{selectedItem}}</pre> </div>
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.