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

2024-02-24

抱歉新手问题。 但是我如何从选择框中获取所选元素的索引并运行函数。我下面的代码不会触发 switchView() 函数。

<select id="selectbox" @change="switchView(index)">
  <option [v-for="(item, index) in items" v-bind:value="item.title"]>
    {{ item.title }}
  </option>
</select>

任何帮助将不胜感激。

EDITED: moved @change="switchView(index)" from <option> to <select>,感谢@Phil

我需要索引,因为我有几个计算项。我需要根据用户对项目的选择来更改视图。


Pass $event.target.selectedIndex到你的函数

Use the @change监听更改事件的指令。调用你的函数并pass the $event或事件目标的选定索引$event.target.selectedIndex作为函数的参数。

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

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

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

完整示例https://jsfiddle.net/3p7rhjyw/ https://jsfiddle.net/tobiobeck/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 文档有关HTMLSelectElement.selectedIndex https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 vue.js 获取所选选项的索引 的相关文章

随机推荐