Skip to content

hackcharms/vue3-toaster

Repository files navigation

Vue3 Toaster

Index

Introduction

Revolutionize your Vue.js 3 development with vue3-toaster, a lightweight and fully customizable toast notification package that seamlessly blends into your design, requiring zero third-party dependencies for a cleaner bundle size and offering effortless customization to match your exact design requirements. Easily integrate toast notifications into your Vue.js components and tailor their look and feel to match your exact requirements. Easy-to-use composables and plugins for effortless integration.

How to Install

using NPM

npm i vue3-toaster

using Yarn

yarn add vue3-toaster

How to use

There are mainly two ways to use vue3-toaster package.

Register as plugin

in vue

//main.ts/.js
import ToastPlugin from "vue3-toaster";
createApp(App)
  .use(ToastPlugin, {
    closable: false,
    //.. other options
  })
  .mount("#app");
<!-- App.vue -->
<template>
  <div>
    <!-- you don't need to import the ToastContainer component, it's auto imported in plugin -->
    <ToastContainer />
    <!--  Other stuffs -->
  </div>
</template>

in nuxt

import ToastPlugin from "vue3-toaster";
export default defineNuxtPlugin((_nuxtApp) => {
  _nuxtApp.vueApp.use(ToastPlugin, {
    closable: false,
    pauseOnHover: false,
    closeOnDoubleClick: true,
    // other options ToastContainerConfig
  });
});
<!-- layouts/default.vue -->
<template>
  <div>
    <!-- you don't need to import the ToastContainer component, it's auto imported in plugin -->
    <ToastContainer />
    <slot />
    <!--  Other stuffs -->
  </div>
</template>

Direct import

Vue.js project

<!-- App.vue -->
<script lang="ts" setup>
  import { ToastContainer, ToastContainerConfig } from "vue3-toaster";
  const defaultOptions: ToastContainerConfig = {
    pauseOnHover: true,
    closable: true,
    closeOnDoubleClick: false,
    theme: {
      //
    },
  };
</script>
<template>
  <div>
    <ToastContainer v-bind="defaultOptions" />
    <!--  Other stuffs -->
  </div>
</template>
<!-- MyComponent.vue -->
<script lang="ts" setup>
  import { useToaster } from "vue3-toaster";
  function toast() {
    useToaster().add({
      type:'info',
      title:'Congratulations'
      text:'You have successfully completed.'
      });
    useToaster().success('this is My success toaster');
  }
</script>
<template>
  <div>
    <!--  Your component templated here -->
  </div>
</template>

CodeSandBox Composition Api example

Nuxt.js Project

for Nuxt js project code would be same, you just need to put in your layouts. eg

<!-- layouts/default.vue -->
<script lang="ts" setup>
  import {
    ToastContainer,
    ToastContainerConfig,
    useToasterConfig,
  } from "vue3-toaster";
  const defaultOptions: ToastContainerConfig = {
    pauseOnHover: true,
    closable: true,
    closeOnDoubleClick: false,
    theme: {
      //
    },
  };
  useToasterConfig().update(defaultOptions);
</script>
<template>
  <div>
    <!-- you don't need to import the ToastContainer component, it's auto imported in plugin -->
    <ToastContainer />
    <slot />
    <!--  Other stuffs -->
  </div>
</template>

Please Note:- <ToastContainer v-bind="defaultOptions"/> and useToasterConfig().update(defaultOptions); are alternative of each other it's recommended to use only one of them.

How to fire toast (working example)

Using Composable (Composition API)

import { useToaster } from "vue3-toaster";
// let for some use case I want only this toast message to be cleared after some event executed
function performSomeTask() {
  const ToasterId = useToaster().add({
    title: "Server Error",
    type: "error",
    text: "Please try again after some time.",
  });
  // in next try we got success response so we don't want it to be visible so we will remove it.
  useToaster().remove(ToasterId);
}

Using inject method (if registerd as a plugin in (Composition API))

import { useToaster } from "vue3-toaster";
const toaster = inject("$toaster");
const ToasterId = toaster.add({
  title: Congratulations,
  type: success,
  text: "You have Done it.",
});

Using this (if registerd as a plugin (Option API))

export default {
  methods: {
    fireToast() {
      const ToasterId = this.$toaster.add({
        title: Congratulations,
        type: success,
        text: "You have Done it.",
      });
    },
  },
};

CodeSandBox Option Api example

Interfaces

name description
ToastVariant main Cont
ToastContainerTheme Interface for Theme
ToastContainerConfig Interface for available option for plugin registration
ToastProps Interface for Toast message
ToastSlotType Available Slots for component

ToastVariant

type ToastVariant = "warn" | "success" | "info" | "error";

ToastContainerTheme

export type ToastContainerTheme = {
  zIndex: string | number;
  top: string;
  bottom: string;
  left: string;
  right: string;
  iconSize: string;
  successColor: string;
  warnColor: string;
  infoColor: string;
  errorColor: string;
  gray: string;
  toasterMaxWidth: string;
  animationDuration: number;
  animationFunction:
    | "linear"
    | "ease"
    | "ease-in"
    | "ease-out"
    | "ease-in-out"
    | "step-end"
    | "step-start"
    | `cubic-bezier(${number},${number},${number},${number})`;
  toastBackgroundColor: string;
  translateX: string;
  direction: -1 | 1;
};

ToastContainerConfig

export type ToastContainerConfig = {
  theme: Partial<ToastContainerTheme>;
  pauseOnHover: boolean;
  closable: boolean;
  closeOnDoubleClick: boolean;
  duration: number;
};
type ToastSlotProps = Readonly<
  ToastProps & {
    destroyToaster: () => void;
    pauseCountdown: (value: boolean) => void;
  }
>;

ToastSlotType

export type ToastSlotType = {
  default(props: ToastSlotProps): any;
  icon(props: Pick<ToastSlotProps, "type">): any;
  clearIcon(props: {}): any;
  content(props: Pick<ToastSlotProps, "type" | "text" | "title">): any;
};

ToastProps

export interface ToastProps {
  id: string;
  title: string;
  type: ToastVariant;
  text: string;
  options: Partial<Exclude<ToastContainerConfig, "theme">>;
}

Toaster

export interface Toaster {
  add(_toastObj: Partial<ToastProps>): string;
  success(message: string): string | undefined;
  info(message: string): string | undefined;
  warn(message: string): string | undefined;
  error(message: string): string | undefined;
  remove(_toastId: string): string | void;
  clear(_toastIds?: string[]): void;
  toasters: ComputedRef<ToastProps[]>;
}

UseToasterConfigType

interface UseToasterConfigType {
  update(Option: ToastContainerConfig): ComputedRef<ToastContainerConfig>;
  all: ComputedRef<ToastContainerConfig>;
  cssVariables: Record<string, string>;
}

Plugin Properties

import ToastContainer from "../components/ToastContainer.vue";

interface PluginProperties{
    $toaster: Toaster;
    ToastContainer: typeof ToastContainer;
    globalProperties: {
      $toaster: Toaster;
    };
  }

Composable

name Interface description
useToaster Toaster Composable to manipulate toaster
useToasterConfig UseToasterConfigType Composable to manipulate toaster Config

useToaster

It implements the Toaster interface, following are the purpose of it's methods and data.

  • add

    useToaster().add() method is the most flexible method, it takes Partial<ToastProps> as argument where you can define the title if you want to use it different than the native titles and many more option to control the UI and UX. You can check the ToastProps interface for more details.
  • success

    useToaster().success() accept string and create toaster with title as Success.
  • info

    useToaster().info() accept string and create toaster with title as Information.
  • warn

    useToaster().warn() accept string and create toaster with title as Warning.
  • error

    useToaster().error() accept string and create toaster with title as Error.

Note: - All above methods return a unique uuid that can be use to manually remove the toast component before it expired.

useToasterConfig

It take cares of configuration of theme and options, it implements UseToasterConfigType, it has following methods

  • update

useToasterConfig().update() method is used to update the global config of toaster.

note:- Alternatively you can pass props in <ToastContainer/> component same as shown in the Vue.js project section

  • all

    useToasterConfig().all it return the all applied global configurations.
  • cssVariables

    useToasterConfig().cssVariables it return the converted global theme options values in css variables.
  • default configuration

export const defaultConfig: ToastContainerConfig = {
  theme: {
    zIndex: 9999,
    top: "0",
    bottom: "auto",
    left: "0",
    right: "auto",
    iconSize: "40px",
    successColor: "#2bde3f",
    warnColor: "#ffc007",
    infoColor: "#1d72f3",
    errorColor: "#de0909",
    gray: "#aaaaaa",
    toasterMaxWidth: "500px",
    animationDuration: 1000,
    animationFunction: "ease-in-out",
    translateX: "200px",
    direction: 1,
    toastBackgroundColor: "#ffff",
  },
  closable: true,
  pauseOnHover: true,
  closeOnDoubleClick: true,
  duration: 10,
};

Slots

image

Slots interface had been defined here ToastSlotType, there are 4 slots provided by the component.

1. default

interface {
  id: string;
  title: string;
  type: ToastVariant;
  text: string;
  destroyToaster: () => void;
  pauseCountdown: (value: boolean) => void;
}

2. icon

interface {
  type: "warn" | "success" | "info" | "error";
  title: string;
}

3. clearIcon

interface {
}

4. content

interface {
  type: "warn" | "success" | "info" | "error";
  title: string;
  text: string;
}