How to get index of selected option with vue.js
Pass $event.target.selectedIndex
to your function
Use the @change
directive to listen to the change event. Invoke your function and pass the $event
or the selected index of the event target $event.target.selectedIndex
as a parameter to your function.
<select @change="switchView($event, $event.target.selectedIndex)">
Your method receives the passed parameters.
methods: {
switchView: function(event, selectedIndex) {
console.log(event, selectedIndex);
}
}
Full Example https://jsfiddle.net/3p7rhjyw/
<div id="app">
<select @change="switchView($event, $event.target.selectedIndex)">
<option v-for="(item, index) in items" v-bind:value="item.title">
{{ item.title }}
</option>
</select>
<p>
{{ selectedIndex }} {{ items[selectedIndex].id }}
</p>
</div>
<script>
new Vue({
el: "#app",
data: {
items: [
{ title: "Learn JavaScript", id: 'A' },
{ title: "Learn Vue", id: 'B' },
{ title: "Play around in JSFiddle", id: 'C' },
{ title: "Build something awesome", id: 'D' }
],
selectedIndex: 0
},
methods: {
switchView: function(event, selectedIndex) {
console.log(event, selectedIndex);
this.selectedIndex = selectedIndex;
}
}
});
</script>
Mozilla documentation about HTMLSelectElement.selectedIndex.
You can use @change
on select
element and get the index with help of indexOf function. Here is working demo.
See code:
var demo = new Vue({
el: '#demo',
data: function(){
return {
age: '',
selectedIndex: '',
options: [1,2,3,44,55]
};
},
methods: {
selected: function () {
this.selectedIndex = this.options.indexOf(this.age)
alert('this is selected Index ' + this.selectedIndex)
}
}
})