如何使用 vue.js 获取所选选项的索引 [英] How to get index of selected option with vue.js
本文介绍了如何使用 vue.js 获取所选选项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
抱歉新手问题.但是如何从选择框中获取所选元素的索引并运行函数.我下面的代码不会触发 switchView() 函数.
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>
任何帮助将不胜感激.
已将 @change="switchView(index)"
从 移动到
,感谢 @Phil
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.
推荐答案
您可以在 select
元素上使用 @change
并在 indexOf 函数.这是演示.
You can use @change
on select
element and get the index with help of indexOf function. Here is working demo.
查看代码:
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)
}
}
})
这篇关于如何使用 vue.js 获取所选选项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文