使用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的延迟,允许退出动画。
API
useToast()
useToast组合件提供了全局管理吐司通知的方法。
add()
add(toast: Partial<Toast>): Toast
添加新的吐司通知。
参数
toast
Partial<Toast> required
具有以下属性的部分
Toast对象:id
string | number
吐司的唯一标识符。如果未提供,则会生成唯一的id。重用现有的id将合并到该吐司中,而不是添加新的id。
open
boolean
吐司是否打开。请转到
true。title
string | VNode | (() => VNode)
在吐司中显示的标题。
description
string | VNode | (() => VNode)
吐司中显示的描述。
icon
string
吐司中显示的图标。
avatar
AvatarProps
在吐司中显示的头像。请参阅Avatar。
color
string
吐司的颜色。从黄色到
primary。orientation
'horizontal' | 'vertical'
内容和操作之间的方向。请参阅
vertical。close
boolean | Omit<ButtonProps, LinkPropsKeys>
自定义或隐藏关闭按钮(使用
false值)。将其设置为true。closeIcon
string
关闭按钮中显示的图标。
actions
ButtonProps[]
吐司中显示的操作。请参阅Button。
progress
boolean | Pick<ProgressProps, 'color' | 'ui'>
自定义或隐藏进度条(使用
false值)。将其设置为true。duration
number
onClick
(toast: Toast) => void
点击吐司时调用的回调函数。
onUpdateOpen
(open: boolean) => void
当吐司打开状态改变时调用的回调函数。当吐司关闭时(过期或解散)执行操作时很有用。
type
'foreground' | 'background'
辅助技术如何宣布吐司。使用
background进行非用户直接操作的祝酒。as
any
吐司呈现为
li的. xml的元素或组件。**返回:**添加的完整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>