42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import { defineStore } from 'pinia';
|
|
import { ref } from 'vue';
|
|
import type { Toast, ToastType } from '@/types/toast';
|
|
|
|
export const useToastStore = defineStore('toast', () => {
|
|
const toasts = ref<Toast[]>([]);
|
|
|
|
const showToast = (message: string, type: ToastType = 'info', duration?: number) => {
|
|
const id = Math.random().toString(36).substring(7);
|
|
const newToast: Toast = { id, message, type, duration };
|
|
toasts.value.push(newToast);
|
|
|
|
setTimeout(() => {
|
|
closeToast(id);
|
|
}, duration || 3000);
|
|
|
|
return id;
|
|
};
|
|
|
|
const closeToast = (id: string) => {
|
|
const index = toasts.value.findIndex(t => t.id === id);
|
|
if (index > -1) {
|
|
toasts.value.splice(index, 1);
|
|
}
|
|
};
|
|
|
|
const success = (message: string, duration?: number) => showToast(message, 'success', duration);
|
|
const error = (message: string, duration?: number) => showToast(message, 'error', duration);
|
|
const warning = (message: string, duration?: number) => showToast(message, 'warning', duration);
|
|
const info = (message: string, duration?: number) => showToast(message, 'info', duration);
|
|
|
|
return {
|
|
toasts,
|
|
showToast,
|
|
closeToast,
|
|
success,
|
|
error,
|
|
warning,
|
|
info,
|
|
};
|
|
});
|