[Vuejs]-Catch the index of a v-for looping and pass the index to a function

0👍

You can read the selectedIndex property directly

new Vue({
  el: '#app',
  data: {
    users: [{_id: 1, name: "user 1"}, {_id: 2, name: "user 2"}]
  },
  methods: {
    onChange(event) {
      console.log("index is " + event.target.selectedIndex)
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <select @change="onChange">
    <option v-for="user in users" :value="user._id">{{user.name}}</option>
  </select>
</div>

0👍

Here is one way you can handle this. First, you’ll need to move your @change event handler up to the <select/> element. Then you can use the special $event variable to get the index of the selected option (the selectedIndex). While this isn’t the index variable from your v-for loop, the value should be the same.

Here’s the updated code:

<select name="userSelect" id="userSelect" class="custom-select" @change="takeProperty($event.target.selectedIndex)">
  <option :value="user._id" v-for="(user,index) in getUser" :key="index" >{{  user.nome  }}</option>
</select>

Leave a comment