2
<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
  • 1
    You can pass the iterated properties into your method as arguments, eg myMethod(n, index) Commented Oct 16, 2018 at 2:59

2 Answers 2

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.net/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.net/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>

Sign up to request clarification or add additional context in comments.

Comments

4

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.