Ralph
Ralph

Reputation: 37

Passing Multiple Arguments to a Custom Event in Vue

According to the Vue documentation - I linked to the relevant page - I can emit a custom event together with a value by typing <ChildComponent @click="$emit('myEvent', 1)" /> and, if the event handler on the parent component is a method, this value will be passed as its argument. But what if I want to pass another argument to the handler when calling it in the parent component? Can I simply write <ParentComponent @myEvent="eventHandler(2)" /> and then have the function accept two arguments, like this?

function eventHandler(childArgument, parentArgument) {
  // I want to have access to the value 1 from the child and the value 2 from the parent component here.
  // If I do it like this, will childArgument contain the 1 and parentArgument the 2?
}

And if this doesn't work, how would I have to do this?

Upvotes: 0

Views: 1681

Answers (1)

vanhops
vanhops

Reputation: 61

I just recently did this in my project. In your example of a ChildComponent and ParentComponent you can have

<ChildComponent @click="$emit('myEvent', 1)" />

<ParentComponent @myEvent="eventHandler(2, ...arguments)" />

Then your eventHandler would look like this

function eventHandler(parentArgument, childArgument) { ... }

You can probably change the ordering as you wish but this worked for me. Also just a side note I believe it's recommended to use kebab-case for the html elements.

Upvotes: 3

Related Questions