Last active
June 7, 2024 17:42
-
-
Save JonasDoebertin/e87cb10df9393c3fb4c99731191cad23 to your computer and use it in GitHub Desktop.
Building a global event bus for Vue.js
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
// Using the most basic event bus | |
import Vue from 'vue'; | |
import Bus from './basic'; | |
Vue.component('my-first-component', { | |
methods: { | |
sampleClickAction() { | |
Bus.$emit('my-sample-event'); | |
} | |
} | |
}); | |
Vue.component('my-second-component', { | |
created() { | |
Bus.$on('my-sample-event', () => { | |
// Do something… | |
}); | |
} | |
}); |
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
// The most basic event bus | |
// Imprt vue.js | |
import Vue from 'vue'; | |
// Create empty vue.js instance to use as event bus | |
const Bus = new Vue({}); | |
// Export event bus instance | |
export default Bus; |
Another example, using the bus in a slightly different way.
// events.ts
import { Component, Vue } from "vue-property-decorator";
import debounce from "debounce";
// b-img-lazy nested inside b-carousel issue
// see https://github.com/bootstrap-vue/bootstrap-vue/issues/1210
const updateCarouselImages = debounce(() => {
window.dispatchEvent(new Event("scroll"));
}, 100);
@Component
class EventBus extends Vue {
created() {
this.$on("b:carousel:img:next", updateCarouselImages);
}
beforeDestroy() {
this.$off("b:carousel:img:next", updateCarouselImages);
}
}
export default new EventBus();
// thumbnail.ts
import { Component, Vue } from "vue-property-decorator";
import eventBus from "@/lib/events";
@Component
export default class Thumbnail extends Vue {
mounted() {
eventBus.$emit("b:carousel:img:next");
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do not forget the .$off in beforeDestroy to avoid memory leak