Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Forked from loilo/bubble.md
Created May 7, 2022 23:17
Show Gist options
  • Save DominikStyp/6e5d4b567e4a56c027b7bfcd64057039 to your computer and use it in GitHub Desktop.
Save DominikStyp/6e5d4b567e4a56c027b7bfcd64057039 to your computer and use it in GitHub Desktop.
Make Vue events bubble

Make Vue events bubble

Vue events don't bubble the component tree on their own. However when writing wrapper components this can be the desired behaviour.

This code registers a global bubble directive which allows to re-emit all given events:

Let's say we want to bubble events start, accelerate and brake of our component Car.

Without any help, we'd roughly have to do this:

<Car
  @start="(...args) => $emit('start', ...args)"
  @accelerate="(...args) => $emit('accelerate', ...args)"
  @brake="(...args) => $emit('brake', ...args)"
  />

However with this directive, we can just do the following:

<Car v-bubble.start.accelerate.brake />

That's it! :)

Vue.directive('bubble', (el, binding, vnode) => {
Object.keys(binding.modifiers).forEach(event => {
// Bubble events of Vue components
if (vnode.componentInstance) {
vnode.componentInstance.$on(event, (...args) => {
vnode.context.$emit(event, ...args)
})
// Bubble events of native DOM elements
} else {
el.addEventListener(event, payload => {
vnode.context.$emit(event, payload)
})
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment