vue-sonner

repository·main·Indexed 23 days ago

https://github.com/xiaoluoboding/vue-sonner

An opinionated, customizable toast component for Vue applications, ported from the React 'sonner' library. It features swipe-to-dismiss animations, high-quality default styling, and support for Vue 3 and Nuxt 3. The library provides various toast types including success, error, action, and promise-based notifications, as well as support for custom Vue components and headless (unstyled) toasts for Tailwind CSS integration.

Tokens
5.9K
Snippets
20
Records
45
Agent score
77%

What's inside vue-sonner

  1. Tailwind CSS integration

    main

    To use Tailwind CSS, set unstyled: true in toastOptions (globally) or the toast() options (individually). This allows you to use the classes object to map Tailwind classes to specific toast elements.

    <Toaster
      :toastOptions="{
        unstyled: true,
        classes: {
          toast: 'bg-blue-400',
          title: 'text-red-400',
          description: 'text-red-400',
          actionButton: 'bg-zinc-400',
          cancelButton: 'bg-orange-400',
          closeButton: 'bg-lime-400'
        }
      }"
    />
  2. Usage in Nuxt 3

    main

    For Nuxt 3, use the official vue-sonner/nuxt module. You can configure the module in nuxt.config.ts. Once configured, use the <Toaster /> component and the $toast function provided via useNuxtApp().

    // nuxt.config.ts
    export default defineNuxtConfig({
      ...
      modules: ['vue-sonner/nuxt'],
      vueSonner: {
        css: false // true by default to include css file
      }
    })
    <!-- app.vue -->
    <template>
      <div>
        <Toaster position="top-right" />
        <button @click="() => $toast('My first toast')">Render a toast</button>
      </div>
    </template>
    
    <script setup lang="ts">
      const { $toast } = useNuxtApp()
    </script>
  3. Usage in Vue 3

    main

    To use vue-sonner in a Vue 3 application, import the Toaster component and the toast function. You must also import the library's CSS file. Place the <Toaster /> component at the root of your application (e.g., in App.vue).

    <!-- App.vue -->
    <template>
      <Toaster />
      <button @click="() => toast('My first toast')">Render a toast</button>
    </template>
    
    <script lang="ts" setup>
      import 'vue-sonner/style.css'
      import { Toaster, toast } from 'vue-sonner'
    </script>
  4. Configure Toaster props (Theme, Position, Expanded)

    main

    The <Toaster /> component accepts several props for global configuration:

    • theme: Sets the theme (light is default; use dark for dark mode).
    • position: Sets the screen position (top-left, top-center, top-right, bottom-left, bottom-center, bottom-right). Default is top-right.
    • expand: Boolean to expand toasts by default.
    • visibleToasts: Number of visible toasts (default is 3).
    • closeButton: Boolean to show a close button on hover.
    • richColors: Boolean to enable colorful error/success states.
    • offset: Custom offset from screen edges (e.g., 80px).
    • hotkey: Array of event.code values to override the default focus hotkey (default is ⌥/alt + T).
  5. Global and Individual Styling

    main

    You can style toasts globally via the toastOptions prop on <Toaster /> or individually via the options object in toast().

    Global Styling:

    <Toaster
      :toastOptions="{
        style: { background: 'red' },
        class: 'my-toast',
        descriptionClass: 'my-toast-description'
      }"
    />

    Individual Styling:

    toast('Event has been created', {
      style: { background: 'red' },
      class: 'my-toast',
      descriptionClass: 'my-toast-description'
    })
  6. Use promise-based toasts

    main

    The library supports promise-based toasts via the promise property in ToastT. This allows a toast to automatically transition through loading, success, and error states based on the lifecycle of a Promise.

    • loading: Content to show while the promise is pending.
    • success: Content to show when the promise resolves.
    • error: Content to show when the promise rejects.
    • description: Optional description for the states.
    • finally: A callback executed when the promise settles.
  7. Use VueSonner via CDN (UMD build)

    main

    For browser-based usage without a build step, you can include Vue and VueSonner via script tags. The plugin automatically exposes window.toast globally, allowing you to trigger toasts from plain JavaScript or anywhere in your application.

    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/vue-sonner"></script>
    <script>
      const app = Vue.createApp({})
      app.use(VueSonner)
      app.mount('#app')
    
      // Toast usage anywhere (even outside Vue)
      toast.success('This works globally!')
    </script>
  8. Access toast in Vue components

    main

    Once the plugin is installed via app.use(VueSonner), you can access the toast functionality using either the Options API or the Composition API.

    Options API

    The $toast property is added to all component instances.

    Composition API

    You can use Vue's dependency injection to retrieve the toast instance using the 'toast' injection key.

    // Inside a Vue component (Options API)
    this.$toast.success('Message sent!')
    
    // Inside a Vue component (Composition API)
    import { inject } from 'vue'
    const toast = inject('toast')
    toast?.error('Something went wrong!')
  9. Promise toast

    main

    Starts in a loading state and automatically updates when the provided promise resolves or fails. You can use functions for success and error to incorporate the promise result into the toast message.

    toast.promise(() => new Promise((resolve) => setTimeout(resolve, 2000)), {
      loading: 'Loading',
      success: (data: any) => 'Success',
      error: (data: any) => 'Error'
    })