admin管理员组文章数量:1401307
<div v-for="(n, index) in items" :id="n" @click="myMethod($event)">{{n}}</div>
The array is like
items: [mouse, bull, tiger, rabbit, pig, cat, dog, horse]
The method is like
myMethod: function(event){
console.log(event.target.id);
}
I want to click each div and that div tells me its content, so I bind the content to the id of each div. The problem is I can't access the index of the items in myMethod()
. I want to use the index of each item for other purposes. How can I access them? Currently I can only pass data to the method through the id attribute.
<div v-for="(n, index) in items" :id="n" @click="myMethod($event)">{{n}}</div>
The array is like
items: [mouse, bull, tiger, rabbit, pig, cat, dog, horse]
The method is like
myMethod: function(event){
console.log(event.target.id);
}
I want to click each div and that div tells me its content, so I bind the content to the id of each div. The problem is I can't access the index of the items in myMethod()
. I want to use the index of each item for other purposes. How can I access them? Currently I can only pass data to the method through the id attribute.
-
1
You can pass the iterated properties into your method as arguments, eg
myMethod(n, index)
– Phil Commented Oct 16, 2018 at 2:59
2 Answers
Reset to default 6I want to use the index of each item for other purposes. How can I access them?
It's very simple, just passing it, like this:
<div v-for="(n, index) in items" :id="n" @click="myMethod(index)">{{n}}</div>
This is a working example on CodeSandbox: https://codesandbox.io/s/m363rl73oy
Another demo:
var app = new Vue({
el: '#app',
data: {
items: ['mouse', 'bull', 'tiger', 'rabbit', 'pig', 'cat', 'dog', 'horse']
},
methods: {
handleClick: function(index) {
alert(index)
}
}
})
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<div @click="handleClick(index)" v-for="(item, index) in items" :key="index">{{item}}</div>
</div>
In case you want to pass data to the method, just passing it, like this
var app = new Vue({
el: '#app',
data: {
items: ['mouse', 'bull', 'tiger', 'rabbit', 'pig', 'cat', 'dog', 'horse']
},
methods: {
handleClick: function(item) {
alert(item)
}
}
})
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<div @click="handleClick(item)" v-for="(item, index) in items" :key="index">{{item}}</div>
</div>
You can pass the index into the method like this.
<div v-for="(n, index) in items" :id="n" @click="myMethod($event, index)">{{n}}</div>
本文标签: javascriptVue click event for arraysStack Overflow
版权声明:本文标题:javascript - Vue click event for arrays - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744216527a2595664.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论