Services
useToast
Composable per mostrare notifiche toast tramite pattern inject/provide.
Firma TypeScript
export function useToast(): ToastService
export interface ToastService {
add: (message: ToastMessage) => number;
remove: (id: number) => void;
removeAll: () => void;
info: (message: string, title?: string) => number;
success: (message: string, title?: string) => number;
warn: (message: string, title?: string) => number;
error: (message: string, title?: string) => number;
}
Parametri
Nessun parametro. Il composable recupera il servizio tramite inject(ToastServiceKey).
Valore di Ritorno
| Proprietà | Tipo | Descrizione |
|---|---|---|
add | (message: ToastMessage) => number | Aggiunge un toast con configurazione completa; ritorna l'ID univoco |
remove | (id: number) => void | Rimuove un toast tramite il suo ID |
removeAll | () => void | Rimuove tutte le notifiche toast attive |
info | (message: string, title?: string) => number | Shortcut per toast informativo (severity: info) |
success | (message: string, title?: string) => number | Shortcut per toast di successo (severity: success) |
warn | (message: string, title?: string) => number | Shortcut per toast di avviso (severity: warn) |
error | (message: string, title?: string) => number | Shortcut per toast di errore (severity: error) |
Esempio
import { useToast } from '@pzeta/vue-components'
const toast = useToast()
// Shortcut per severità comuni
toast.success('Dati salvati con successo')
toast.error('Si è verificato un errore')
toast.warn('Attenzione: dati non salvati')
toast.info('Informazione importante')
// Configurazione completa
const id = toast.add({
severity: 'success',
title: 'Successo',
message: 'Operazione completata',
life: 3000
})
// Rimozione manuale
toast.remove(id)
// Uso in un flusso async
const salva = async () => {
try {
await api.save(data)
toast.success('Dati salvati con successo')
} catch {
toast.error('Errore durante il salvataggio')
}
}
Prerequisiti
Il componente <Toast /> deve essere montato nella gerarchia di antenati del componente che usa useToast(). Il componente Toast esegue il provide del ToastService tramite ToastServiceKey.
<!-- App.vue -->
<template>
<Toast />
<RouterView />
</template>
Note
- Lancia un
Errorse ilToastServicenon è stato fornito (componente<Toast />non montato). - Il pattern è simile a PrimeVue 4
useToast. - Gli ID restituiti da
add,info,success,warn,errorpossono essere usati conremove()per dismiss programmatico. - Il tipo
ToastMessagedefinisce le opzioni complete:severity,title,message,life(ms),sticky, ecc.