/ app / composables / useToast.ts
useToast.ts
 1  import { ref } from "vue";
 2  
 3  interface Toast {
 4    id: string;
 5    message: string;
 6    type: string;
 7  }
 8  
 9  const toasts = ref<Toast[]>([]);
10  let nextId = 0;
11  
12  export const useToast = (
13    msg?: string,
14    toastType = "error",
15    duration = 5000,
16  ) => {
17    const show = (text: string, msgType = "error", msgDuration = 3000) => {
18      if (!text || text.trim() === "") {
19        return;
20      }
21  
22      const id = `toast-${nextId++}`;
23      const toast = { id, message: text, type: msgType };
24      toasts.value.push(toast);
25  
26      setTimeout(() => {
27        hideById(id);
28      }, msgDuration);
29    };
30  
31    const error = (text: string, msgDuration = 3000) =>
32      show(text, "error", msgDuration);
33  
34    const success = (text: string, msgDuration = 3000) =>
35      show(text, "success", msgDuration);
36  
37    const hideById = (id: string) => {
38      const index = toasts.value.findIndex((toast) => toast.id === id);
39      if (index !== -1) {
40        toasts.value.splice(index, 1);
41      }
42    };
43  
44    const hide = () => {
45      toasts.value = [];
46    };
47  
48    if (msg) {
49      show(msg, toastType, duration);
50    }
51  
52    return {
53      toasts,
54      show,
55      error,
56      success,
57      hide,
58      hideById,
59    };
60  };