使用Toast

一个可以在应用中显示吐司通知的组合。

用法

使用自动导入的useToast组合文件显示Toast通知。

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

function showToast() {
  toast.add({
    title: 'New message',
    description: 'You have a new message from Benjamin.',
    actions: [{
      icon: 'i-lucide-reply',
      label: 'Reply',
      color: 'neutral',
      variant: 'outline',
      onClick: () => {
        toast.add({ title: 'Reply sent', color: 'success' })
      }
    }]
  })
}
</script>

<template>
  <UButton label="Show toast" @click="showToast" />
</template>
  • useToast组合使用Nuxt的useState来管理吐司状态,确保整个应用程序的反应性。
  • 默认情况下,一次最多显示5个toast。当添加超过此限制的新吐司时,最旧的吐司将自动删除。请使用App组件上的toaster.max属性更改它。
  • 当删除一个吐司时,在它实际从状态中删除之前有200 ms的延迟,允许退出动画。
请确保使用App组件包装您的应用程序,该组件使用我们的Toaster组件,该组件使用Reka UI中的ToastProvider组件。
在Toast组件文档中了解如何自定义toast的外观和行为。

API

useToast()

useToast组合件提供了全局管理吐司通知的方法。

add()

add(toast: Partial<Toast>): Toast

添加新的吐司通知。

参数

toast
Partial<Toast> required
具有以下属性的部分Toast对象:

**返回:**添加的完整Toast对象。

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

function showToast() {
  toast.add({
    title: 'Success',
    description: 'Your action was completed successfully.',
    color: 'success'
  })
}
</script>

update()

update(id: string | number, toast: Omit<Partial<Toast>, 'id'>): void

更新现有吐司通知。

参数

id
string | number required
要更新的吐司的唯一标识符。
toast
Omit<Partial<Toast>, 'id'> required
具有要更新的属性的部分Toast对象。不能更改id,将重新打开吐司,并且duration将重置,除非您再次传递它。
<script setup lang="ts">
const toast = useToast()

function updateToast(id: string | number) {
  toast.update(id, {
    title: 'Updated Toast',
    description: 'This toast has been updated.'
  })
}
</script>

remove()

remove(id: string | number): void

吐司通知。

参数

id
string | number required
要删除的吐司的唯一标识符。
<script setup lang="ts">
const toast = useToast()

function removeToast(id: string | number) {
  toast.remove(id)
}
</script>

clear()

clear(): void

所有吐司通知。

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

function clearAllToasts() {
  toast.clear()
}
</script>

toasts

toasts: Ref<Toast[]>

一个包含所有当前吐司通知的反应数组。

<script setup lang="ts">
const { toasts } = useToast()
</script>

<template>
  <div>
    <pre>{{ toasts }}</pre>
  </div>
</template>