D
D
Dmitry Gololobov2019-04-15 07:21:44
Vue.js
Dmitry Gololobov, 2019-04-15 07:21:44

How to get the index of a list item when clicking on a link inside it?

There is a pattern

<li v-for="(element, index) in elements" :key="index"><a href="#" @click="getElement">{{ element.param }}</a></li>

We need to run the getElement method so that it knows which element I clicked on. Those. either pass the index of the list element into it, or the entire value of element. That being said, I need to use preventDefault on the link.
Now the getElement method looks like this:
getElement(e) {
 e.preventDefault()
 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Malyarov, 2019-04-15
@dGololobov

<li v-for="(element, index) in elements" :key="index"><a href="#" @click="getElement(index)">{{ element.param }}</a></li>

getElement(index) {
 e.preventDefault()
 
}

For the future, do this: console.log(e)
This will show you all the information about the event (the element index is also there)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question