问题
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:
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>
回答2:
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>
回答3:
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.
来源:https://stackoverflow.com/questions/56391231/click-event-in-vuejs-on-custom-component