[英]How to get index of selected option with vue.js
對不起,新手問題。 但是如何從選擇框中獲取所選元素的索引並運行函數。 我下面的代碼不會觸發 switchView() 函數。
<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)"
從<option>
到<select>
,感謝@Phil
我需要索引,因為我有幾個計算項目。 我需要根據用戶從項目中的選擇來更改視圖。
$event.target.selectedIndex
傳遞給您的函數使用@change
指令來監聽change 事件。 調用你的函數並通過$event
或事件目標的選定索引$event.target.selectedIndex
作為參數傳遞給你的函數。
<select @change="switchView($event, $event.target.selectedIndex)">
您的方法接收傳遞的參數。
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>
關於HTMLSelectElement.selectedIndex 的Mozilla 文檔。
您可以在select
元素上使用@change
並在indexOf函數的幫助下獲取索引。 這是工作演示。
見代碼:
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)
}
}
})
對於預先修改的 bootstrap-vue,此事件處理可能與$event.target.selectedIndex不同。 特別是對於 Vue 3,這個答案可能會節省您的時間。
<b-form-select @change="onChange" :options="options"></b-form-select>
從用戶選擇接收事件的方法。
methods: {
onChange: function(event) {
let index = event.target.selectedIndex
}
}
完整示例可能如下所示:
<div id="app">
<select @change="onChange">
</select>
<p>Selected index: {{ selectedIndex }}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
items: [
"option 1",
"option 2",
"option 3",
"option 4"
],
selectedIndex: 0
},
methods: {
onChange: function(event) {
let index = event.target.selectedIndex // this selectedIndex is from event.
this.selectedIndex = index
}
}
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.