1

I have in my main component one custom component and I need to fire a custom event on click, I tried it in this way:

<child-component @click="fireCustomEvent"></child-component>

This does not work and I tried to solve this problem with adding @click.native

<child-component @click.native="fireCustomEvent"></child-component>

With .native it works but it fires the event every time if I click inside my "child-component".

Can I avoid somehow to fire this event again if I click inside "child-component"?

1
  • If you bind the click on a div, the event will be triggered when any of the component inside is clicked. Maybe you should explain what do you want to click and what not. Show us what is inside your <child-component>. Commented May 31, 2019 at 9:12

3 Answers 3

4

To do this you need the click handler inside your child component and then emit an event to the parent.

In child component:

//child component
<template>
   <div @click="$emit('wasClicked')")>click here</div>
</template>

In parent component:

//parent component
<template>
   ...
   <child-component @wasClicked="fireCustomEvent"></child-component>
</template>
Sign up to request clarification or add additional context in comments.

4 Comments

But the problem is @click does not work on custom component. Is that not possible?
Sure @click works, but the way you have it <child-component @click="..."> here it would be listening for an emited "click" event from inside the child component itself. @click is shorthand for v-on:click and works a bit different when used on a child component. vuejs.org/v2/guide/…
it works. many thanks. Is there ok to pass some data like: $emit('wasClicked', category.id)? Can I get then the data from this event in child component?
Yes certainly you can pass data with the emitted event and use it your "fireCustomEvent" method
0

I had a similar problem and I solved it by adding div to wrap the custom component and it worked. So try this it should do the job.

<div @click="fireCustomEvent">
    <child-component></child-component>
</div>

Comments

-1

You should show the code in the component that emit the event.

You must have something like this:

//code that trigger an click event
this.$emit('click');

//or if you you to pass some data
this.$emit('click','some_data');

.native doesn't need to be used here.

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.