Marco Tesini
Marco Tesini

Reputation: 13

Click event in vuejs on custom component?

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"?

Upvotes: 1

Views: 6128

Answers (3)

Marek Barta
Marek Barta

Reputation: 389

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>

Upvotes: 0

Slim
Slim

Reputation: 1276

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.

Upvotes: -1

skribe
skribe

Reputation: 3615

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>

Upvotes: 4

Related Questions