How to handle global notifications?
I'd like to show a notification component whenever an event (like an API response) is triggered on any page. Right now I have to include the component on each page separately because there doesn't seem to be a way to listen to events on the layout itself. I've found several solutions for Nuxt 2 (like $nuxt.$emit => $nuxt.$on) but none of them work with Nuxt 3. I've also tried implementing Mitt (https://github.com/developit/mitt) but Nuxt 3 doesn't like that one either.
Is there maybe some other way how to achieve this?
GitHub
GitHub - developit/mitt: 🥊 Tiny 200 byte functional event emitter /...
🥊 Tiny 200 byte functional event emitter / pubsub. - GitHub - developit/mitt: 🥊 Tiny 200 byte functional event emitter / pubsub.
10 Replies
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Hi, why not use a useState composable?
It’s built into nuxt
Or use Pinia
Nuxt
State Management
Nuxt provides useState composable to create a reactive and SSR-friendly shared state.
Thanks, but isn't this more for keeping data in the store? In my use case these notifications come and go and shouldn't actually be preserved after being shown once
Yeah kind of, but with pinia you can also define an action which displays a notification. However, it's often the case that notifications are stored in an array while they are displayed and then removed when their timeout is over.
If you don't want to install pinia, you could also create a composable like
or
And then since composables are auto imported, in your whole app you could just do
useNotification().create({ message: 'Hello' })
Alright that sounds like a plan, will also check out Pinia. Thank you. 🙂
You could always put the notification component in a layout that all pages use, and then have that component watch for some sort of global state change as a result of your API calls.
You mean with useState?
Yeah, you can use useState, or pinia. I find Pinia to be easier since the devtools support is so strong and you can see exactly what's happening in your store at all times.
I will definitely try Pinia. Right now I've found a quick workaround by using mitt as a plugin, but using the store feels more "nuxty"