I'm trying to set up my InertiaJs / VueJs 3 / Laravel application with a simple way to emit and listen to the events - commonly known as an event bus.
I've done some digging and have come across the mitt package, which I've registered as a global variable on the vue instance using the following approach:
createInertiaApp({
resolve: (name) => {
const page = require(`./Pages/${name}`).default;
page.layout = page.layout || AppLayout;
return page;
},
setup ({ el, App, props, plugin }) {
const emitter = mitt();
const myApp = createApp({
render: () => h(App, props),
});
myApp.config.globalProperties.$emitter = emitter;
myApp.use(plugin).mount(el);
emitter.on('error', (payload) => alert(payload));
}
});
Now, problem I have is the fact that I'm using <script setup> and it doesn't seem like I don't have access to the global variables from this section.
<script setup>
const submit = () => {
$emitter.emit('error', 'An error occurred');
};
</script>
Calling submit method in the above example throws and error saying:
Uncaught ReferenceError: $emitter is not defined
I also tried using getCurrentInstance, but again without any luck.
Is there any way to make it work with <script setup> at all?