gpt4 book ai didi

javascript - 如何使用 vue.js 获取所选选项的索引

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:09 26 4
gpt4 key购买 nike

抱歉新手问题。但是我如何从选择框中获取所选元素的索引并运行函数。我下面的代码不会触发 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

我需要索引,因为我有几个计算项。我需要根据用户从项目中的选择更改 View 。

最佳答案

$event.target.selectedIndex 传递给您的函数

使用@change 指令来监听变化事件。调用您的函数并将 $event 或事件目标的选定索引 $event.target.selectedIndex 作为参数传递到你的功能。

<select @change="switchView($event, $event.target.selectedIndex)">

您的方法接收传递的参数。

  methods: {
switchView: function(event, selectedIndex) {
console.log(event, selectedIndex);
}
}

完整示例 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>

关于 HTMLSelectElement.selectedIndex 的 Mozilla 文档.

关于javascript - 如何使用 vue.js 获取所选选项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42381756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com