1

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?

0

1 Answer 1

0

in your script setup, use:

const instance= getCurrentInstance()

let emitter=instance.appContext.config.globalProperties.$emitter;

emitter.emit('error', 'an error occurred');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.