最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue click event for arrays - Stack Overflow

programmeradmin8浏览0评论
<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.

Share Improve this question asked Oct 16, 2018 at 2:56 JackJackJackJack 6323 gold badges12 silver badges29 bronze badges 1
  • 1 You can pass the iterated properties into your method as arguments, eg myMethod(n, index) – Phil Commented Oct 16, 2018 at 2:59
Add a ment  | 

2 Answers 2

Reset to default 6

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/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>
发布评论

评论列表(0)

  1. 暂无评论