简体   繁体   中英

Vue click event for arrays

<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, index)">{{n}}</div>

I 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.net/npm/vue@2.5.17/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.net/npm/vue@2.5.17/dist/vue.js"></script> <div id="app"> <div @click="handleClick(item)" v-for="(item, index) in items" :key="index">{{item}}</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM