Toast

Eine kurze Nachricht, um dem Benutzer Informationen oder Feedback zu geben.

Bearbeiten

Verwenden Sie die useToast composable, um einen Toast in Ihrer Anwendung anzuzeigen.

<script setup lang="ts">
const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

  toast.add({
    title: 'Event added to calendar',
    description: `This event is scheduled for ${formattedDate}.`,
    icon: 'i-lucide-calendar-days'
  })
}
</script>

<template>
  <UButton
    label="Add to calendar"
    color="neutral"
    variant="outline"
    icon="i-lucide-plus"
    @click="addToCalendar"
  />
</template>
Stellen Sie sicher, dass Sie Ihre App mit der Komponente App umhüllen, die unsere Komponente [Toaster``Toasterhttps://github.com/nuxt/ui/blob/v4/src/runtime/components/Toaster.vue) verwendet, die die Komponente ToastProvider von Reka UI verwendet.
Sie können die App-Komponente toaster prop überprüfen, um zu sehen, wie der Toaster global konfiguriert wird.

title Übersetzung

Übergeben Sie ein Feld title an die Methode toast.add, um einen Titel anzuzeigen.

<script setup lang="ts">
const props = defineProps<{
  title: string
}>()

const toast = useToast()

function showToast() {
  toast.add(props)
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Beschreibung

Übergeben Sie ein Feld description an die Methode toast.add, um eine Beschreibung anzuzeigen.

<script setup lang="ts">
const props = defineProps<{
  title: string
  description: string
}>()

const toast = useToast()

function showToast() {
  toast.add(props)
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Icon (nicht)

Übergeben Sie ein icon-Feld an die toast.add-Methode, um eine Icon anzuzeigen.

<script setup lang="ts">
const props = defineProps<{
  icon: string
}>()

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    icon: props.icon
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Avatar (englisch)

Übergeben Sie ein avatar-Feld an die toast.add-Methode, um einen Avatar anzuzeigen.

<script setup lang="ts">
import type { AvatarProps } from '@nuxt/ui'

const props = defineProps<{
  avatar: AvatarProps
}>()

const toast = useToast()

function showToast() {
  toast.add({
    title: 'User invited',
    description: 'benjamincanac was invited to the team.',
    avatar: props.avatar
  })
}
</script>

<template>
  <UButton label="Invite user" color="neutral" variant="outline" @click="showToast" />
</template>

color kaufen

Übergeben Sie ein color-Feld an die toast.add-Methode, um die Farbe des Toast zu ändern.

<script setup lang="ts">
import type { ToastProps } from '@nuxt/ui'

const props = defineProps<{
  color: ToastProps['color']
}>()

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    icon: 'i-lucide-wifi',
    color: props.color
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Schließen

Übergeben Sie ein close-Feld zum Anpassen oder Ausblenden des schließenden Button (mit dem Wert false).

<script setup lang="ts">
const toast = useToast()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    icon: 'i-lucide-wifi',
    close: {
      color: 'primary',
      variant: 'outline',
      class: 'rounded-full'
    }
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Close Icon (nicht vorhanden)

Übergeben Sie ein closeIcon-Feld, um die Schaltfläche zum Schließen Icon anzupassen. Standardmäßig i-lucide-x.

<script setup lang="ts">
const props = defineProps<{
  closeIcon: string
}>()

const toast = useToast()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    closeIcon: props.closeIcon
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>
Sie können dieses Symbol global in Ihrem app.config.ts unter ui.icons.close Schlüssel anpassen.
Sie können dieses Symbol global in Ihrem vite.config.ts unter ui.icons.close Schlüssel anpassen.

Actions Bearbeiten

Übergeben Sie ein actions-Feld, um einige Button-Aktionen zum Toast hinzuzufügen.

<script setup lang="ts">
const toast = useToast()

const props = defineProps<{
  description: string
}>()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: props.description,
    actions: [{
      icon: 'i-lucide-refresh-cw',
      label: 'Retry',
      color: 'neutral',
      variant: 'outline',
      onClick: (e) => {
        e?.stopPropagation()
      }
    }]
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Duration Bearbeiten

Übergeben Sie ein duration-Feld an die toast.add-Methode, um zu ändern, wie lange der Toast sichtbar bleibt (in Millisekunden). Standardmäßig auf 5000.

Setzen Sie das Feld duration auf 0, um Toast offen zu halten, bis es manuell geschlossen wird.
<script setup lang="ts">
const toast = useToast()

const props = defineProps<{
  duration: number
}>()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    duration: props.duration
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Progress (englisch)

Übergeben Sie ein progress-Feld, um die Progress-Leiste (mit dem Wert false) anzupassen oder auszublenden

Der Fortschrittsbalken erbt standardmäßig die Toastfarbe, Sie können sie jedoch mit dem Feld progress.color überschreiben.
<script setup lang="ts">
const toast = useToast()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    description: 'There was a problem with your request.',
    icon: 'i-lucide-wifi',
    progress: false
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Orientierung.

Übergeben Sie ein orientation-Feld an die toast.add-Methode, um die Ausrichtung des Toast zu ändern.

<script setup lang="ts">
const toast = useToast()

const props = defineProps<{
  orientation: 'horizontal' | 'vertical'
}>()

function showToast() {
  toast.add({
    title: 'Uh oh! Something went wrong.',
    orientation: props.orientation,
    actions: [{
      icon: 'i-lucide-refresh-cw',
      label: 'Retry',
      color: 'neutral',
      variant: 'outline',
      onClick: (e) => {
        e?.stopPropagation()
      }
    }]
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Examples Bearbeiten

Die Nuxt-Benutzeroberfläche bietet eine App-Komponente, die Ihre App umhüllt, um globale Konfigurationen bereitzustellen.

Globale Position ändern.

Ändern Sie die toaster.position-Prop auf der App-Komponente, um die Position der Toasts zu ändern.

app.vue
<script setup lang="ts">
const toaster = { position: 'bottom-right' }
</script>

<template>
  <UApp :toaster="toaster">
    <NuxtPage />
  </UApp>
</template>
<script setup lang="ts">
const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

  toast.add({
    title: 'Event added to calendar',
    description: `This event is scheduled for ${formattedDate}.`,
    icon: 'i-lucide-calendar-days'
  })
}
</script>

<template>
  <UButton
    label="Add to calendar"
    color="neutral"
    variant="outline"
    icon="i-lucide-plus"
    @click="addToCalendar"
  />
</template>

Change global duration (globale Dauer ändern)

Ändern Sie die toaster.duration-Prop auf der App-Komponente, um die Dauer der Toast zu ändern.

app.vue
<script setup lang="ts">
const toaster = { duration: 5000 }
</script>

<template>
  <UApp :toaster="toaster">
    <NuxtPage />
  </UApp>
</template>
<script setup lang="ts">
const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

  toast.add({
    title: 'Event added to calendar',
    description: `This event is scheduled for ${formattedDate}.`,
    icon: 'i-lucide-calendar-days'
  })
}
</script>

<template>
  <UButton
    label="Add to calendar"
    color="neutral"
    variant="outline"
    icon="i-lucide-plus"
    @click="addToCalendar"
  />
</template>

Change global max: badge{label="4.1+" class="align-text-top"} (Globale max ändern: badge{label="4.1+" class="align-text-top"})

Ändern Sie die toaster.max-Prop auf der App-Komponente, um die maximale Anzahl von Toasts zu ändern, die gleichzeitig angezeigt werden.

app.vue
<script setup lang="ts">
const toaster = { max: 3 }
</script>

<template>
  <UApp :toaster="toaster">
    <NuxtPage />
  </UApp>
</template>
<script setup lang="ts">
const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

  toast.add({
    title: 'Event added to calendar',
    description: `This event is scheduled for ${formattedDate}.`,
    icon: 'i-lucide-calendar-days'
  })
}
</script>

<template>
  <UButton
    label="Add to calendar"
    color="neutral"
    variant="outline"
    icon="i-lucide-plus"
    @click="addToCalendar"
  />
</template>

Stacked Toasts (Deutsche Übersetzung)

Setzen Sie die toaster.expand-Prop auf false auf der App-Komponente, um gestapelte Toasts anzuzeigen (inspiriert von Sonner).

app.vue
<script setup lang="ts">
const toaster = { expand: true }
</script>

<template>
  <UApp :toaster="toaster">
    <NuxtPage />
  </UApp>
</template>
Sie können den Mauszeiger über die Toasts bewegen, um sie zu erweitern. Dies wird auch den Timer der Toasts anhalten.
<script setup lang="ts">
const toast = useToast()

function addToCalendar() {
  const eventDate = new Date(Date.now() + Math.random() * 31536000000)
  const formattedDate = eventDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })

  toast.add({
    title: 'Event added to calendar',
    description: `This event is scheduled for ${formattedDate}.`,
    icon: 'i-lucide-calendar-days'
  })
}
</script>

<template>
  <UButton
    label="Add to calendar"
    color="neutral"
    variant="outline"
    icon="i-lucide-plus"
    @click="addToCalendar"
  />
</template>

Deduplizierte Toasts: badge{label="4.5+" class="align-text-top"}

Wenn Sie toast.add mit einem bereits vorhandenen id aufrufen, wird der vorhandene Toast gepulst, anstatt ein Duplikat zu erstellen.

<script setup lang="ts">
const toast = useToast()

function showToast() {
  toast.add({
    id: 'copy',
    title: 'Copied to clipboard',
    icon: 'i-lucide-circle-check',
    duration: 0
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Mit Rückruf

Übergeben Sie ein onUpdateOpen-Feld, um einen Rückruf auszuführen, wenn der Toast geschlossen ist (entweder durch Ablauf oder Benutzerentlassung).

<script setup lang="ts">
const toast = useToast()

function showToast() {
  const t = toast.add({
    'title': 'Uploading file...',
    'description': 'Your file is being uploaded.',
    'icon': 'i-lucide-cloud-upload',
    'duration': 3000,
    'onUpdate:open': (open: boolean) => {
      if (open) {
        return
      }

      toast.update(t.id, {
        'title': 'File uploaded!',
        'description': 'Your file has been successfully uploaded.',
        'icon': 'i-lucide-check',
        'color': 'success',
        'onUpdate:open': undefined
      })
    }
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

Mit HTML-Inhalten

Verwenden Sie die Renderfunktion h() in den Feldern title oder description, um HTML-Elemente oder Vue-Komponenten mit benutzerdefiniertem Styling zu rendern.

<script setup lang="ts">
const toast = useToast()

function showToast() {
  toast.add({
    title: h('span', {}, [
      'Item ',
      h('span', { class: 'text-primary font-bold' }, '#15'),
      ' deleted'
    ]),
    description: h('span', {}, [
      'You have successfully deleted the item from your ',
      h('span', { class: 'font-bold' }, 'account'),
      '.'
    ]),
    icon: 'i-lucide-trash-2'
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>
<script setup lang="ts">
import { h } from 'vue'

const toast = useToast()

function showToast() {
  toast.add({
    title: h('span', {}, [
      'Item ',
      h('span', { class: 'text-primary font-bold' }, '#15'),
      ' deleted'
    ]),
    description: h('span', {}, [
      'You have successfully deleted the item from your ',
      h('span', { class: 'font-bold' }, 'account'),
      '.'
    ]),
    icon: 'i-lucide-trash-2'
  })
}
</script>

<template>
  <UButton label="Show toast" color="neutral" variant="outline" @click="showToast" />
</template>

API Bearbeiten

Props (nicht)

Prop Default Type
as
'li'
any

The element or component this component should render as.

title
string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }>
description
string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }>
icon
any
avatar
AvatarProps
color
'primary'
"error" | "primary" | "secondary" | "success" | "info" | "warning" | "neutral"
orientation
'vertical'
"vertical" | "horizontal"

The orientation between the content and the actions.

close
true
boolean | Omit<ButtonProps, LinkPropsKeys>

Display a close button to dismiss the toast. { size: 'md', color: 'neutral', variant: 'link' }

closeIcon
appConfig.ui.icons.close
any

The icon displayed in the close button.

actions
ButtonProps[]

Display a list of actions:

  • under the title and description when orientation is vertical
  • next to the close button when orientation is horizontal { size: 'xs' }
duration
5000
number

The time in milliseconds before the toast automatically closes. Overrides the global toaster.duration.

Set to 0 to keep the toast open until it's manually closed.

progress
true
boolean | Pick<ProgressProps, "color" | "ui">

Display a progress bar showing the toast's remaining duration. { size: 'sm' }

defaultOpen
boolean

The open state of the dialog when it is initially rendered. Use when you do not need to control its open state.

open
boolean

The controlled open state of the dialog. Can be bind as v-model:open.

type
"foreground" | "background"

Control the sensitivity of the toast for accessibility purposes.

For toasts that are the result of a user action, choose foreground. Toasts generated from background tasks should use background.

ui
{ root?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; icon?: SlotClass; avatar?: SlotClass; avatarSize?: SlotClass; actions?: SlotClass; progress?: SlotClass; close?: SlotClass; }

Slots Bearbeiten

Slot Type
leading
{ ui: object; }
title
{}
description
{}
actions
{}
close
{ ui: object; }

Emits Bearbeiten

Event Type
pause
[]
escapeKeyDown
[event: KeyboardEvent]
resume
[]
swipeStart
[event: SwipeEvent]
swipeMove
[event: SwipeEvent]
swipeCancel
[event: SwipeEvent]
swipeEnd
[event: SwipeEvent]
update:open
[value: boolean]

Expose (englisch)

Beim Zugriff auf die Komponente über eine Template-Referenz können Sie Folgendes verwenden:

VornameTyp
height nichtRef<number> nicht

Theme Bearbeiten

app.config.ts
export default defineAppConfig({
  ui: {
    toast: {
      slots: {
        root: 'relative group overflow-hidden bg-default shadow-lg rounded-lg ring ring-default p-4 flex gap-2.5',
        wrapper: 'w-0 flex-1 flex flex-col',
        title: 'text-sm font-medium text-highlighted',
        description: 'text-sm text-muted',
        icon: 'shrink-0 size-5',
        avatar: 'shrink-0',
        avatarSize: '2xl',
        actions: 'flex gap-1.5 shrink-0',
        progress: 'absolute inset-x-0 bottom-0',
        close: 'p-0'
      },
      variants: {
        color: {
          primary: {
            root: 'outline-primary/25 focus-visible:outline-3 focus-visible:ring-primary',
            icon: 'text-primary'
          },
          secondary: {
            root: 'outline-secondary/25 focus-visible:outline-3 focus-visible:ring-secondary',
            icon: 'text-secondary'
          },
          success: {
            root: 'outline-success/25 focus-visible:outline-3 focus-visible:ring-success',
            icon: 'text-success'
          },
          info: {
            root: 'outline-info/25 focus-visible:outline-3 focus-visible:ring-info',
            icon: 'text-info'
          },
          warning: {
            root: 'outline-warning/25 focus-visible:outline-3 focus-visible:ring-warning',
            icon: 'text-warning'
          },
          error: {
            root: 'outline-error/25 focus-visible:outline-3 focus-visible:ring-error',
            icon: 'text-error'
          },
          neutral: {
            root: 'outline-inverted/25 focus-visible:outline-3 focus-visible:ring-inverted',
            icon: 'text-highlighted'
          }
        },
        orientation: {
          horizontal: {
            root: 'items-center',
            actions: 'items-center'
          },
          vertical: {
            root: 'items-start',
            actions: 'items-start mt-2.5'
          }
        },
        title: {
          true: {
            description: 'mt-1'
          }
        }
      },
      defaultVariants: {
        color: 'primary'
      }
    }
  }
})
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ui from '@nuxt/ui/vite'

export default defineConfig({
  plugins: [
    vue(),
    ui({
      ui: {
        toast: {
          slots: {
            root: 'relative group overflow-hidden bg-default shadow-lg rounded-lg ring ring-default p-4 flex gap-2.5',
            wrapper: 'w-0 flex-1 flex flex-col',
            title: 'text-sm font-medium text-highlighted',
            description: 'text-sm text-muted',
            icon: 'shrink-0 size-5',
            avatar: 'shrink-0',
            avatarSize: '2xl',
            actions: 'flex gap-1.5 shrink-0',
            progress: 'absolute inset-x-0 bottom-0',
            close: 'p-0'
          },
          variants: {
            color: {
              primary: {
                root: 'outline-primary/25 focus-visible:outline-3 focus-visible:ring-primary',
                icon: 'text-primary'
              },
              secondary: {
                root: 'outline-secondary/25 focus-visible:outline-3 focus-visible:ring-secondary',
                icon: 'text-secondary'
              },
              success: {
                root: 'outline-success/25 focus-visible:outline-3 focus-visible:ring-success',
                icon: 'text-success'
              },
              info: {
                root: 'outline-info/25 focus-visible:outline-3 focus-visible:ring-info',
                icon: 'text-info'
              },
              warning: {
                root: 'outline-warning/25 focus-visible:outline-3 focus-visible:ring-warning',
                icon: 'text-warning'
              },
              error: {
                root: 'outline-error/25 focus-visible:outline-3 focus-visible:ring-error',
                icon: 'text-error'
              },
              neutral: {
                root: 'outline-inverted/25 focus-visible:outline-3 focus-visible:ring-inverted',
                icon: 'text-highlighted'
              }
            },
            orientation: {
              horizontal: {
                root: 'items-center',
                actions: 'items-center'
              },
              vertical: {
                root: 'items-start',
                actions: 'items-start mt-2.5'
              }
            },
            title: {
              true: {
                description: 'mt-1'
              }
            }
          },
          defaultVariants: {
            color: 'primary'
          }
        }
      }
    })
  ]
})

Changelog (englisch)

No recent changes