0

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?

2 Answers 2

3

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.

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

Comments

0

I handled it like this:

<Child @click="$emit('emitted-child-data', 'child-data')" /> 
<ParentComp @emitted-child-data="handleData($event, parentData)" 

Then, in the "handleData" method:

handleData(childEmittedData, parentData) {...} 

The $event is a vue-specific keyword variable that gets automatically passed the native DOM event and has the value equivalent to event.target.value. When using the event-listeners with v-on (or @ ), the native DOM event automatically gets passed to $event . That being said, when you call a method name in the listener like this:

// without passing arguments into "handleSubmit" from this level
<ParentComp @emitted-child-data="handleData" />

...the $event gets automatically passed into "handleSubmit" when called. Then the body of the method can access the emitted data from the child.

However, if you pass arguments into the method, like this:

@submitted-data="handleSubmit(parentData)"

...the $event (native DOM event) doesn't get auto passed into the method. You need to delebrately pass it in like this:

@submitted-data="handleSubmit($event, parentData)

Now the method "handleSubmit" can be pass the child emitted data (via $event ) and the parentData data.

Hope this helps

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.