0

I have a Laravel 10 application and I am trying to register a global function in Vue 3. I want to be able to call a flash function from anywhere in my application. I am trying to create a Vue instance and then call $emit on that instance. However, when I call the method in Chrome devtools, I get a '$emit is not a function' message. In Vue 2 you could new up an instance of Vue using window.events = new Vue() but apparently that changed in Vue 3

this is in my bootstrap.js file:

import {createApp } from 'vue';
import Flash from "@/Components/Flash.vue";
window.events = createApp(Flash);
window.flash = function (message, level = 'success') {
    window.events.$emit('flash', { message, level });
};

Flash.vue

<template>
    <div class="alert alert-flash"
         :class="'alert-'+level"
         role="alert"
         v-show="show"
         v-text="body">
    </div>
</template>

<script>
export default {
    props: ['message'],
    data() {
        return {
            body: this.message,
            level: 'success',
            show: false
        }
    },
    created() {
        if (this.message) {
            this.flash();
        }
        window.event.$on(
            'flash', data => this.flash(data)
        );
    },
    methods: {
        flash(data) {
            if (data) {
                this.body = data.message;
                this.level = data.level;
            }
            this.show = true;
            this.hide();
        },
        hide() {
            setTimeout(() => {
                this.show = false;
            }, 3000);
        }
Tom Morison
  • 564
  • 1
  • 8
  • 26
  • Global event bus is a potential antipattern, especially when you use it within the same app. There are other ways to achieve the same goal like global store. There are already things like window events https://developer.mozilla.org/en-US/docs/Web/API/Window/message_event – Estus Flask Apr 14 '23 at 05:59

0 Answers0