vue-toastification

repository·next·Indexed 25 days ago

https://github.com/maronato/vue-toastification

A lightweight, highly customizable toast notification library for Vue 3. It supports TypeScript, RTL, custom components, and advanced lifecycle hooks. Version 2.0.0-rc.5 provides a composable `useToast()` interface for triggering success, info, error, and warning toasts both inside and outside Vue components.

Tokens
6K
Snippets
16
Records
37
Agent score
82%

What's inside vue-toastification

  1. Migrate from v1.x to v2.x

    next

    When upgrading to v2.x, note the following breaking changes:

    • Vue Version Support: Vue 2 support has been dropped in favor of Vue 3.
    • Accessing Toasts: this.$toast is no longer available. You must use the useToast composable to obtain the toast interface. The object returned by useToast is identical to the old this.$toast and contains the same methods.
    • Transition Duration: The transitionDuration option is deprecated due to changes in Vue's transition system. To control transition timing, you should instead change or override the transition classes.
  2. Install vue-toastification for Vue 3

    next

    To use Vue Toastification with Vue 3, install the @next version using your preferred package manager.

    Note: This version is exclusively compatible with Vue 3+. If you are using Vue 2, you must install the v1 branch instead.

    $ yarn add vue-toastification@next
    $ npm install --save vue-toastification@next
  3. Register the Vue Toastification plugin

    next

    To use Vue Toastification, add it as a plugin to your Vue application. You must also import the default CSS file. You can pass an optional options object to set global defaults during registration.

    For TypeScript users, use the PluginOptions type for the options object.

    import { createApp } from "vue";
    import Toast from "vue-toastification";
    // Import the CSS or use your own!
    import "vue-toastification/dist/index.css";
    
    const app = createApp(...);
    
    const options = {
        // You can set your default options here
    };
    
    app.use(Toast, options);
  4. Render custom components in toasts

    next

    You can render Vue Single File Components (SFCs), JSX, or complex objects as toast content.

    Passing a Component

    Pass the component directly: toast(MyComponent).

    Closing from within a component

    Emit the close-toast event from inside your custom component to close the toast programmatically.

    Passing Props and Listeners

    Pass an object with component, props, and listeners keys. Note that props passed this way are not reactive.

    JSX

    Pass a JSX template directly.

    // Render a component
    import MyComponent from "./MyComponent.vue";
    tost(MyComponent);
    
    // Render with props and events
    const content = {
        component: MyComponent,
        props: {
            myProp: "abc",
            otherProp: 123
        },
        listeners: {
            click: () => console.log("Clicked!"),
            myEvent: myEventHandler
        }
    };
    tost(content);
    
    // Render JSX
    const myJSX = (
        <div>
            <h1
                >My Title</h1
            <span
                >My text</span
        </div
    );
    tost(myJSX);
  5. Provide a toast instance to a component subtree with provideToast

    next

    Use provideToast within a component's setup() function to create a new Vue Toastification instance that is only available to that component and its children. This is useful for scoping toast containers to specific parts of your application. Child components can then access this instance using useToast() without arguments.

    <!-- Parent component -->
    <script>
      import { provideToast } from "vue-toastification";
    
      export default {
        setup() {
          provideToast({
            timeout: 1000
          })
        }
      }
    </script>
    
    <!-- Child components -->
    <script>
      import { useToast } from "vue-toastification";
      import { defineComponent } from "vue";
    
      export default defineComponent({
        setup() {
          // This will access the instance provided by the parent
          const toast = useToast()
        }
      })
    </script>
  6. Use toasts outside Vue components

    next

    Because the plugin uses a global event bus by default, you can use useToast() anywhere in your application (e.g., in a Vuex store) without being inside a component.

    // store.js
    import { createStore } from 'vuex'
    import { useToast } from 'vue-toastification'
    
    const toast = useToast()
    
    const store = createStore({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment (context) {
          context.commit('increment')
          toast.success("incremented!")
        }
      }
    })
  7. Configure Vue Toastification via Plugin Registration

    next

    When registering the plugin using app.use(), you can define global default settings for all toasts.

    Available Options:

    • position: Screen position. Options: top-right, top-center, top-left, bottom-right, bottom-center, bottom-left. (Default: top-right)
    • newestOnTop: Whether newest toasts are at the top of the stack. (Default: true)
    • maxToasts: Maximum toasts per stack. (Default: 20)
    • transition: Vue Transition name or object with enter-active, leave-active, and move classes. (Default: Vue-Toastification__bounce)
    • draggable: Enable/disable dragging to dismiss. (Default: true)
    • draggablePercent: Percentage of width to drag before dismissal (0 to 1). (Default: 0.6)
    • pauseOnFocusLoss: Pause toast when window loses focus. (Default: true)
    • pauseOnHover: Pause toast on mouse hover. (Default: true)
    • closeOnClick: Close toast when clicked. (Default: true)
    • timeout: Auto-dismissal time in ms, or false to disable. (Default: 5000)
    • container: HTMLElement or function returning one where toasts mount. (Default: document.body)
    • toastClassName: Custom classes for the toast.
    • bodyClassName: Custom classes for the toast body.
    • hideProgressBar: Hide the progress bar. (Default: false)
    • icon: Custom icon. true uses type-based defaults, false disables. Can be an object: { iconClass: String, iconChildren: String, iconTag: String }.
    • toastDefaults: Object to configure default options per toast type.
    • filterBeforeCreate: Callback (toast, toasts) => toast | false to filter before creation.
    • filterToasts: Callback (toasts) => filteredToasts to filter created toasts.
    • closeButtonClassName: Custom classes for the close button.
    • closeButton: Custom component, JSX, or HTML tag for the close button. (Default: "button")
    • showCloseButtonOnHover: Only show close button on hover. (Default: false)
    • containerClassName: Extra classes for toast containers.
    • onMounted: Callback (containerApp, containerComponent) => void when container mounts.
    • accessibility: { toastRole?: string; closeButtonLabel?: string }. (Default: { toastRole: "alert", closeButtonLabel: "close" })
    • rtl: Enable Right to Left layout. (Default: false)
    • shareAppContext: Share main app context. (Default: false)
  8. Register the VueToastificationPlugin

    next

    To use vue-toastification in your Vue application, register the VueToastificationPlugin during the app installation phase. You can optionally pass a PluginOptions object to configure global settings.

    If you set shareAppContext: true in your options, the plugin will automatically capture the current Vue App instance and use it for context sharing.

  9. Create new Vue Toastification instances with createToastInterface

    next

    You can create independent Vue Toastification instances by using createToastInterface. Each call creates a new Vue App and a separate toast container. This allows you to manage multiple independent toast systems. The function accepts the same PluginOptions used during plugin registration.

    import { createToastInterface } from "vue-toastification";
    
    // Create a default instance
    const myInterface = createToastInterface();
    
    // Create an instance with specific options
    const myInterface = createToastInterface({
      timeout: 1000
    });
  10. Create toasts using useToast()

    next

    Inside a Vue component's setup() function, call useToast() to get the toast interface. You can then trigger different types of toasts (success, info, error, warning) or a default toast. Options passed to a specific toast call will override the global plugin options.

    <script>
      import { useToast } from "vue-toastification";
    
      export default {
        setup() {
          // Get toast interface
          const toast = useToast();
    
          // Use it!
          toast("I'm a toast!");
    
          // or with options
          toast.success("My toast content", {
            timeout: 2000
          });
    
          // Make it available inside methods
          return { toast }
        },
    
        methods: {
          myMethod() {
            // Since you returned `toast` from setup(), you can access it now
            this.toast.info("I'm an info toast!");
          }
        }
      }
    </script>
  11. Create a Toast with Content and Options

    next

    To create a toast, provide content and an optional options object.

    Note: Individual toast options supersede global Plugin Registration settings.

    Content Formats

    You can pass the following as content:

    • String
    • Vue Component
    • JSX
    • Object (for component rendering):
      • component: The Vue Component or JSX to render.
      • props: Object of non-reactive props passed to the component.
      • listeners: Object of event handlers for component emissions.

    Toast Options

    Commonly used options for individual toasts:

    • id: Unique identifier (String or Number).
    • type: success, error, default, info, or warning.
    • position: Override global position.
    • onClick: Callback (closeToast) => void executed when clicked.
    • onClose: Callback executed when the toast is closed.
    • timeout: Override auto-dismissal time.
    • icon: Override icon settings.