[Vuejs]-Stop custom events from propagating to the root component in Vue 3

0👍

It looks weird, but it is actually not the custom event bubbling up, but the listener propagating down.

Here is what happens:

  • Your App.vue sets an event listener on the GeneriqueButton button component
  • GeneriqueButton does not declare an event by that name, so the listener is added to fallthrough attributes (the component’s attr object)
  • Since GeneriqueButton has a single root element, attrs are passed on to the root node, including the listener
  • GeneriqueButton also adds another event listener on BaseButton for the same event
  • BaseButton emits the (undeclared) event and both listeners are called

Note that .stop will stop event propagation on native events, you could use it on the @click on the button to stop the click event from bubbling. It does not work on custom events, which do not bubble at all.

Here is what you can do to avoid the situation:

  • do not set the event handler on App.vue, unless you explicitly want it to be passed to the nested single root element
  • make GeneriqueButton a non-single root element
  • disable fallthrough attributes on GeneriqueButton, as suggested by @TazHinkle

1👍

As per the documentation of Vue3.JS custom events not falls under default event bubbling like native events.

Unlike native DOM events, component-emitted events do not bubble. You can only listen to the events emitted by a direct child component. If there is a need to communicate between sibling or deeply nested components, use an external event bus or a global state management solution.

Leave a comment