useToast Composable
Toast notification system with positioning, auto-dismiss and custom styles
Code
import { ref, type Ref } from 'vue';
type ToastType = 'success' | 'error' | 'warning' | 'info';
interface Toast {
id: string;
message: string;
type: ToastType;
duration?: number;
position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'center';
}
export function useToast() {
const toasts = ref<Toast[]>([]) as Ref<Toast[]>;
const generateId = () => `toast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const showToast = (options: {
message: string;
type?: ToastType;
duration?: number;
position?: Toast['position'];
}) => {
const toast: Toast = {
id: generateId(),
message: options.message,
type: options.type || 'info',
duration: options.duration || 3000,
position: options.position || 'top-right'
};
toasts.value.push(toast);
// Auto dismiss
__TOKEN_48__ (toast.duration && toast.duration > 0) {
setTimeout(() => {
removeToast(toast.id);
}, toast.duration);
}
return toast.id;
};
const removeToast = (id: string) => {
toasts.value = toasts.value.filter(toast => toast.id !== id);
};
const clearToasts = (position?: Toast['position']) => {
__TOKEN_52__ (position) {
toasts.value = toasts.value.filter(toast => toast.position !== position);
} else {
toasts.value = [];
}
};
// Convenience methods
const success = (message: string, options?: Omit<Parameters<typeof showToast>[0], 'message' | 'type'>) =>
showToast({ message, type: 'success', ...options });
const error = (message: string, options?: Omit<Parameters<typeof showToast>[0], 'message' | 'type'>) =>
showToast({ message, type: 'error', ...options });
const warning = (message: string, options?: Omit<Parameters<typeof showToast>[0], 'message' | 'type'>) =>
showToast({ message, type: 'warning', ...options });
const info = (message: string, options?: Omit<Parameters<typeof showToast>[0], 'message' | 'type'>) =>
showToast({ message, type: 'info', ...options });
return {
toasts,
showToast,
removeToast,
clearToasts,
success,
error,
warning,
info
};
}
// Usage example
// const { success, error, toasts } = useToast();
// success('Operation completed!', { duration: 4000 });
// error('Something went wrong!');