Maronato / vue-toastification

Vue notifications made easy!
https://vue-toastification.maronato.dev
MIT License
3.03k stars 139 forks source link

Nuxt 3 not works #374

Closed odlainepre closed 1 year ago

odlainepre commented 1 year ago

Versions

"vue-toastification": "2.0.0-rc.5",

Describe the bug

Tried diff options to install, did not works for nuxt 3. No any toast.

// plugin/toast.ts
// https://github.com/Maronato/vue-toastification/tree/next
import Toast from "vue-toastification"
import "vue-toastification/dist/index.css"

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.provide('toast', Toast)
})

In component directly:

<script setup lang="ts">
import { useToast } from 'vue-toastification'
import "vue-toastification/dist/index.css";

const toast = useToast()

toast("Default toast")
toast.info("Info toast", { timeout: 0 })
toast.success("Success toast")
toast.error("Error toast")
toast.warning("Warning toast")
</script>
jbjorge commented 1 year ago

How about making it install itself in the vueApp?

import Toast from "vue-toastification";
import "vue-toastification/dist/index.css";

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.use(Toast);
})
odlainepre commented 1 year ago

Nuxt 3.1.1 with Nitro 2.1.1 https://stackoverflow.com/questions/74667905/how-to-use-vue-toastification

Inside plugins/toast.client.ts, not works with SSR

import * as vt from 'vue-toastification'
import "vue-toastification/dist/index.css"

const options = {
    timeout: 5_000,
    position: "bottom-right",
    maxToasts: 3,
    showCloseButtonOnHover: true,
}

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.use(vt.default, options)
    return {
        provide: {
            toast: vt.useToast()
        }
    }
})

Component

<script setup>
//throws an error after production build
//import { useToast } from 'vue-toastification'
//const toast = useToast()
//toast.success('Yay!!!')

//works after production build
const { $toast } = useNuxtApp()
$toast.success('Yay!!!')
</script>
eensander commented 1 year ago

When I applied @nikitamarcius solution to my case:

const { $toast } = useNuxtApp()
$toast.success('Yay!!!')

TypeScript seems to be unable to detect the type of the provided value $toast and thus it is typed as unknown. As a workaround I created a nuxt-shims.d.ts file at the root with the content:

import * as Toast from "vue-toastification";

declare module '#app' {
  function useNuxtApp(): NuxtApp & { $toast: ReturnType<typeof Toast.useToast> };
}

Although this works, I assume this is not the recommended way to do this. If anyone has an alternative solution to $toast being unknown, I would love to hear it.