首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >捕获v-for循环的索引并将该索引传递给函数

捕获v-for循环的索引并将该索引传递给函数
EN

Stack Overflow用户
提问于 2019-05-14 03:05:33
回答 2查看 103关注 0票数 0

我有一个由v-for生成的select,所以它有一个索引,我想在用户选择时获得这个select的索引,这样我就可以在一个函数中使用它,我该怎么做呢?

我已经看了几个教程,但我无法解决它,如果我可以将索引作为全局变量,它也可以解决它,因为然后我将获得变量并在函数中使用它

<label for="userSelect">Selecione o usuario</label><br>
<select name="userSelect" id="userSelect" class="custom-select">
<option :value="user._id" @change="takeProperty" v-for="(user,index) in getUser" :key="index" >{{  user.nome  }}</option>
</select><br>
<label for="userSelect">Selecione a propriedade que ele terá acesso</label><br>
<input type="radio" v-for="(property,j) in listProperty" :key="j">Teste<br>
takeProperty: function(index){
   console.log(index) <= returns undefined
}

我希望能够在用户选择不同的选项时检索select的索引

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-15 00:59:38

您可以直接读取selectedIndex属性

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
EN

Stack Overflow用户

发布于 2019-05-14 03:12:26

这里有一个你可以处理这个问题的方法。首先,您需要将@change事件处理程序上移到<select/>元素。然后,您可以使用特殊的$event变量来获取所选选项( selectedIndex)的索引。虽然这不是v-for循环中的索引变量,但值应该是相同的。

下面是更新后的代码:

<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56118468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档