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àTipoDescrizione
add(message: ToastMessage) => numberAggiunge un toast con configurazione completa; ritorna l'ID univoco
remove(id: number) => voidRimuove un toast tramite il suo ID
removeAll() => voidRimuove tutte le notifiche toast attive
info(message: string, title?: string) => numberShortcut per toast informativo (severity: info)
success(message: string, title?: string) => numberShortcut per toast di successo (severity: success)
warn(message: string, title?: string) => numberShortcut per toast di avviso (severity: warn)
error(message: string, title?: string) => numberShortcut 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 Error se il ToastService non è stato fornito (componente <Toast /> non montato).
  • Il pattern è simile a PrimeVue 4 useToast.
  • Gli ID restituiti da add, info, success, warn, error possono essere usati con remove() per dismiss programmatico.
  • Il tipo ToastMessage definisce le opzioni complete: severity, title, message, life (ms), sticky, ecc.