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