Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Created July 15, 2024 19:36
Show Gist options
  • Save mattkenefick/0deac41cf6efe47e157de11c7cac323c to your computer and use it in GitHub Desktop.
Save mattkenefick/0deac41cf6efe47e157de11c7cac323c to your computer and use it in GitHub Desktop.
Bubble events in Vue 2.0
/**
* Example:
*
* import Vue from 'vue';
* import Dispatch from './dispatch';
* Vue.use(Dispatch);
*
* @author Matt Kenefick <matt@polymermallard.com>
* @package Plugin
* @project Your Project
*/
export default {
install(Vue) {
Vue.prototype.$dispatch = function (eventName, ...args) {
let currentComponent = this;
while (currentComponent) {
currentComponent.$emit(eventName, ...args);
currentComponent = currentComponent.$parent;
}
};
},
};
<template>
<section class="example">
<p>Note that the event from MyFile will automatically bubble up to ComponentA through B and C.</p>
<ComponentA v-on:my-event="HandleMyEvent">
<ComponentB>
<ComponentC>
<MyFile />
</ComponentC>
</ComponentB>
</ComponentA>
</section>
</template>
<template>
<section class="my-file" v-on:click="$dispatch('my-event')">
Click Me
</section>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment