我有一个由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的索引
发布于 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>
发布于 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>
https://stackoverflow.com/questions/56118468
复制相似问题