Click event in vuejs on custom component?

你说的曾经没有我的故事 提交于 2021-02-17 05:37:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!