3

I have a list of objects within a v-for loop:

<div v-for="(element, index) in myArray">
    <child @event-fired="handleEvent(index, dataFromChild)"></child>
</div>

Now I want once the event is fired from the child component, on my handleEvent method, pass the index and the data from the child component.

But now, if I do something like stated above,I get an error on console stating, property or method dataFromChild is not defined....

2
  • FYI, camel-cased event names are often difficult to work with. Vue recommends using kebab-cased, ie @event-fired Commented May 27, 2019 at 1:42
  • @Phil thanks, will consider that from now on, thanks Commented May 27, 2019 at 1:44

3 Answers 3

4

You can bind an arrow function expression in your event handler. For example

<child @event-fired="dataFromChild => handleEvent(index, dataFromChild)"/>

JSFiddle demo (from the Vue boilerplate) ~ https://jsfiddle.net/zmxksv35/

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

Comments

0

You can pass the event and the index in the event listener.

<child @event-fired="handleEvent($event,index)"/>

Comments

-1

Just pass everything into your event handler as a single object.

<div v-for="(element, index) in myArray">
    <child @event-fired="data => handleEvent({ index, data })"></child>
</div>

Then, in your event handler, you can destructure it:

handleEvent({ index, data }) {
    // handle the event
}

1 Comment

@Johhn Ah, I misunderstood what dataFromChild represents.

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.