简体   繁体   English

阵列的Vue单击事件

[英]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. 我想单击每个div,该div会告诉我其内容,因此我将内容绑定到每个div的ID。 The problem is I can't access the index of the items in myMethod() . 问题是我无法访问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. 目前,我只能通过id属性将数据传递给方法。

您可以将索引传递给这样的方法。

<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 这是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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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