Created
July 15, 2024 19:36
-
-
Save mattkenefick/0deac41cf6efe47e157de11c7cac323c to your computer and use it in GitHub Desktop.
Bubble events in Vue 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example: | |
* | |
* import Vue from 'vue'; | |
* import Dispatch from './dispatch'; | |
* Vue.use(Dispatch); | |
* | |
* @author Matt Kenefick <[email protected]> | |
* @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; | |
} | |
}; | |
}, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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