토스트
토스트 (Toast)
Toast는 사용자에게 정보나 피드백을 전달하는 간결한 메시지 컴포넌트예요. useToast 컴포저블을 사용해 앱에서 토스트를 표시할 수 있어요.
출처: Nuxt UI
본문
사용법 (Usage)
useToast 컴포저블을 사용해 애플리케이션에 토스트를 표시할 수 있어요.
<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>
[!WARNING]
앱을
App컴포넌트로 감싸야 해요. 이 컴포넌트는 우리의Toaster컴포넌트를 사용하고, Toaster는 Reka UI의ToastProvider컴포넌트를 사용해요.
[!TIP] See: /docs/components/app#props
App컴포넌트의toasterprop을 확인하면 Toaster를 전역으로 구성하는 방법을 볼 수 있어요.
제목 (Title)
toast.add 메서드에 title 필드를 전달하면 제목을 표시할 수 있어요.
<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>
설명 (Description)
toast.add 메서드에 description 필드를 전달하면 설명을 표시할 수 있어요.
<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)
toast.add 메서드에 icon 필드를 전달해 Icon을 표시할 수 있어요.
<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)
toast.add 메서드에 avatar 필드를 전달해 Avatar를 표시할 수 있어요.
<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)
toast.add 메서드에 color 필드를 전달해 Toast의 색상을 바꿀 수 있어요.
<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>
닫기 (Close)
close 필드를 전달해 닫기 Button을 커스터마이즈하거나 숨길 수 있어요(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)
closeIcon 필드를 전달해 닫기 버튼의 Icon을 커스터마이즈할 수 있어요. 기본값은 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>
Nuxt:
[!TIP] See: /docs/getting-started/integrations/icons/nuxt#theme
app.config.ts안의ui.icons.close키에서 이 아이콘을 전역으로 커스터마이즈할 수 있어요.
Vue:
[!TIP] See: /docs/getting-started/integrations/icons/vue#theme
vite.config.ts안의ui.icons.close키에서 이 아이콘을 전역으로 커스터마이즈할 수 있어요.
액션 (Actions)
actions 필드를 전달해 Toast에 Button 액션을 추가할 수 있어요.
<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)
toast.add 메서드에 duration 필드를 전달해 Toast가 표시되는 시간(밀리초)을 변경할 수 있어요. 기본값은 5000이에요.
[!TIP]
duration필드를0으로 설정하면 수동으로 닫을 때까지 Toast를 열어 둘 수 있어요.
<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)
progress 필드를 전달해 Progress 바를 커스터마이즈하거나 숨길 수 있어요(false 값).
[!TIP]
Progress 바는 기본적으로 Toast 색상을 상속하지만,
progress.color필드로 재정의할 수 있어요.
<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>
방향 (Orientation)
toast.add 메서드에 orientation 필드를 전달해 Toast의 방향을 변경할 수 있어요.
<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)
[!NOTE] See: /docs/components/app
Nuxt UI는 앱을 감싸서 전역 설정을 제공하는 App 컴포넌트를 제공해요.
전역 위치 변경 (Change global position)
App 컴포넌트의 toaster.position prop을 변경해 토스트의 위치를 바꿀 수 있어요.
<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)
App 컴포넌트의 toaster.duration prop을 변경해 토스트의 지속 시간을 바꿀 수 있어요.
<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) 4.1+
App 컴포넌트의 toaster.max prop을 변경해 동시에 표시되는 토스트의 최대 개수를 바꿀 수 있어요.
<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)
App 컴포넌트의 toaster.expand prop을 false로 설정하면 쌓인 토스트를 표시할 수 있어요(Sonner에서 영감을 받았어요).
<script setup lang="ts">
const toaster = { expand: true }
</script>
<template>
<UApp :toaster="toaster">
<NuxtPage />
</UApp>
</template>
[!TIP]
토스트 위에 호버하면 토스트가 확장돼요. 이때 토스트의 타이머도 일시정지돼요.
<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>
중복 제거된 토스트 (Deduplicated toasts) 4.5+
이미 존재하는 id로 toast.add를 호출하면 중복을 만들지 않고 기존 토스트가 펄스(pulse) 애니메이션을 보여줘요.
<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>
콜백과 함께 (With callback)
onUpdateOpen 필드를 전달해 토스트가 닫힐 때(만료되거나 사용자가 닫을 때) 콜백을 실행할 수 있어요.
<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>
HTML 콘텐츠와 함께 (With HTML content)
title 또는 description 필드에서 h() 렌더 함수를 사용해 커스텀 스타일로 HTML 요소나 Vue 컴포넌트를 렌더링할 수 있어요.
<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>
API
Props
/**
* Props for the Toast component
*/
interface ToastProps {
/**
* The element or component this component should render as.
* @default 'li'
*/
as?: any;
title?: string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }> | undefined;
description?: string | VNode<RendererNode, RendererElement, { [key: string]: any; }> | (): VNode<RendererNode, RendererElement, { [key: string]: any; }> | undefined;
icon?: any;
avatar?: AvatarProps | undefined;
/**
* @default 'primary'
*/
color?: "error" | "primary" | "secondary" | "success" | "info" | "warning" | "neutral" | undefined;
/**
* The orientation between the content and the actions.
* @default 'vertical'
*/
orientation?: "vertical" | "horizontal" | undefined;
/**
* Display a close button to dismiss the toast.
* `{ size: 'md', color: 'neutral', variant: 'link' }`{lang="ts-type"}
* @default true
*/
close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
/**
* The icon displayed in the close button.
* @default appConfig.ui.icons.close
*/
closeIcon?: any;
/**
* 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' }`{lang="ts-type"}
*/
actions?: ButtonProps[] | undefined;
/**
* 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.
* @default 5000
*/
duration?: number | undefined;
/**
* Display a progress bar showing the toast's remaining duration.
* `{ size: 'sm' }`{lang="ts-type"}
* @default true
*/
progress?: boolean | Pick<ProgressProps, "color" | "ui"> | undefined;
ui?: { root?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; icon?: SlotClass; avatar?: SlotClass; avatarSize?: SlotClass; actions?: SlotClass; progress?: SlotClass; close?: SlotClass; } | undefined;
/**
* The open state of the dialog when it is initially rendered. Use when you do not need to control its open state.
*/
defaultOpen?: boolean | undefined;
/**
* The controlled open state of the dialog. Can be bind as `v-model:open`.
*/
open?: boolean | undefined;
/**
* 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`.
*/
type?: "foreground" | "background" | undefined;
}
Slots
/**
* Slots for the Toast component
*/
interface ToastSlots {
leading(): any;
title(): any;
description(): any;
actions(): any;
close(): any;
}
Emits
/**
* Emitted events for the Toast component
*/
interface ToastEmits {
pause: (payload: []) => void;
escapeKeyDown: (payload: [event: KeyboardEvent]) => void;
resume: (payload: []) => void;
swipeStart: (payload: [event: SwipeEvent]) => void;
swipeMove: (payload: [event: SwipeEvent]) => void;
swipeCancel: (payload: [event: SwipeEvent]) => void;
swipeEnd: (payload: [event: SwipeEvent]) => void;
update:open: (payload: [value: boolean]) => void;
}
Expose
템플릿 ref로 컴포넌트에 접근할 때 다음을 사용할 수 있어요.
| Name | Type |
|---|---|
height |
Ref<number> |
테마 (Theme)
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'
}
}
}
})