39 lines
1023 B
TypeScript
39 lines
1023 B
TypeScript
import { reactive } from 'vue'
|
|
|
|
export type ToastType = 'success' | 'error' | 'warning' | 'info'
|
|
|
|
export interface Toast {
|
|
id: number
|
|
type: ToastType
|
|
message: string
|
|
duration: number
|
|
}
|
|
|
|
const toasts = reactive<Toast[]>([])
|
|
let nextId = 1
|
|
|
|
function add(message: string, type: ToastType = 'info', duration = 4000): number {
|
|
const id = nextId++
|
|
toasts.push({ id, type, message, duration })
|
|
if (duration > 0) {
|
|
setTimeout(() => remove(id), duration)
|
|
}
|
|
return id
|
|
}
|
|
|
|
function remove(id: number) {
|
|
const index = toasts.findIndex(t => t.id === id)
|
|
if (index !== -1) toasts.splice(index, 1)
|
|
}
|
|
|
|
export function useToast() {
|
|
return {
|
|
toasts,
|
|
success: (msg: string, duration?: number) => add(msg, 'success', duration ?? 4000),
|
|
error: (msg: string, duration?: number) => add(msg, 'error', duration ?? 6000),
|
|
warning: (msg: string, duration?: number) => add(msg, 'warning', duration ?? 5000),
|
|
info: (msg: string, duration?: number) => add(msg, 'info', duration ?? 4000),
|
|
remove,
|
|
}
|
|
}
|