Sorry for newbie question. But how can i get an index of selected element from selectbox and run a function. My code below doesn't trigger switchView() function.
<select id="selectbox" @change="switchView(index)">
<option [v-for="(item, index) in items" v-bind:value="item.title"]>
{{ item.title }}
</option>
</select>
any help will be appreciated.
EDITED:
moved @change="switchView(index)"
from <option>
to <select>
, thanks to @Phil
I need index, because i have several calculated items. And i need change view according to user's selection from items.
Render the Add Item button, and bind the click event. On the click event handler, pass data with random id to the addItem method to add a new list item on clicking the Add Item button.
Single-file components and readability Components represent encapsulated elements of your interface. In Vue. js, components can be written in HTML, CSS, and JavaScript without dividing them into separate files.
$event.target.selectedIndex
to your functionUse 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);
}
}
<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)
}
}
})
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