모달
모달 (Modal)
메시지를 표시하거나 사용자 입력을 요청하는 데 사용할 수 있는 대화상자(dialog) 창 컴포넌트예요. 여러 슬롯, 프로그래매틱 사용, 중첩 모달, 커맨드 팔레트 통합 등을 지원합니다.
출처: Nuxt UI
본문
메시지를 표시하거나 사용자 입력을 요청하는 데 사용할 수 있는 대화상자 창이에요.
사용 방법 (Usage)
Modal의 기본 슬롯에 Button이나 다른 어떤 컴포넌트든 넣어 사용할 수 있어요.
그런 다음 #content 슬롯을 사용해 Modal이 열렸을 때 표시되는 콘텐츠를 추가합니다.
<template>
<UModal>
<UButton label="Open" color="neutral" variant="subtle" />
<template #content>
<Placeholder class="h-48 m-4" />
</template></UModal>
</template>
#header, #body, #footer 슬롯을 사용해 Modal의 콘텐츠를 커스터마이즈할 수도 있어요.
제목 (Title)
title prop을 사용하면 Modal 헤더의 제목을 설정할 수 있어요.
<template>
<UModal title="Modal with title">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
설명 (Description)
description prop을 사용하면 Modal 헤더의 설명을 설정할 수 있어요.
<template>
<UModal title="Modal with description" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
닫기 버튼 (Close)
close prop을 사용하면 Modal 헤더에 표시되는 닫기 버튼을 커스터마이즈하거나(false 값으로) 숨길 수 있어요.
Button 컴포넌트의 어떤 속성이든 전달해 커스터마이즈할 수 있습니다.
<template>
<UModal title="Modal with close button" :close="{
color: 'primary',
variant: 'outline',
class: 'rounded-full'
}">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
[!TIP]
#content슬롯을 사용하면 닫기 버튼은 헤더의 일부이므로 표시되지 않아요.
닫기 아이콘 (Close Icon)
close-icon prop을 사용하면 닫기 버튼 Icon을 커스터마이즈할 수 있어요. 기본값은 i-lucide-x예요.
<template>
<UModal title="Modal with close button" close-icon="i-lucide-arrow-right">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</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키에서 이 아이콘을 전역으로 커스터마이즈할 수 있어요.
트랜지션 (Transition)
transition prop을 사용하면 Modal에 애니메이션이 적용될지 제어할 수 있어요. 기본값은 true예요.
<template>
<UModal :transition="false" title="Modal without transition">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
오버레이 (Overlay)
overlay prop을 사용하면 Modal에 오버레이가 있는지 제어할 수 있어요. 기본값은 true예요.
<template>
<UModal :overlay="false" title="Modal without overlay">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
모달 (Modal)
modal prop을 사용하면 Modal이 외부 콘텐츠와의 상호작용을 막는지 제어할 수 있어요. 기본값은 true예요.
[!NOTE]
modal을false로 설정하면 오버레이가 자동으로 비활성화되고 외부 콘텐츠와 상호작용할 수 있게 됩니다.
<template>
<UModal :modal="false" title="Modal interactive">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
닫기 가능 여부 (Dismissible)
dismissible prop을 사용하면 Modal 바깥을 클릭하거나 escape 키를 눌렀을 때 Modal이 닫힐지 제어할 수 있어요. 기본값은 true예요.
[!NOTE]
사용자가 닫으려고 하면
close:prevent이벤트가 emit 됩니다.
[!TIP]
modal: false와dismissible: false를 조합하면 Modal을 닫지 않고 배경과 상호작용할 수 있어요.
<template>
<UModal :dismissible="false" modal title="Modal non-dismissible">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
스크롤 가능 (Scrollable) 4.2+
scrollable prop을 사용하면 Modal의 콘텐츠가 오버레이 안에서 스크롤되도록 할 수 있어요.
[!WARNING]
스크롤하려면 오버레이가 필요하므로
modal: false는 호환되지 않고,overlay: false는 배경만 제거해요.
<template>
<UModal scrollable overlay title="Modal scrollable">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-full" />
</template></UModal>
</template>
[!CAUTION]
일부 운영체제에서 스크롤바를 클릭하면 대화상자가 의도치 않게 닫히는 알려진 문제가 있어요.
전체 화면 (Fullscreen)
fullscreen prop을 사용하면 Modal을 전체 화면으로 만들 수 있어요.
<template>
<UModal fullscreen title="Modal fullscreen">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-full" />
</template></UModal>
</template>
마운트 해제 (Unmount) 4.10+
unmount-on-hide prop을 사용하면 Modal이 닫혔을 때 Modal의 콘텐츠가 마운트 해제되는 것을 막을 수 있어요. 기본값은 true예요.
<template>
<UModal :unmount-on-hide="false" title="Modal">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template></UModal>
</template>
[!NOTE]
DOM을 검사하면 닫힌 상태에서도 Modal의 콘텐츠가 렌더링되고 있는 것을 볼 수 있어요.
[!TIP]
portalprop을false로 설정하면 콘텐츠가 서버에서도 렌더링됩니다. 이는 페이지 로드 시 깜빡임 없이 열린 Modal을 SSR 중에 렌더링하거나 SEO를 위해 콘텐츠를 노출하는 데 유용해요.
예시 (Examples)
열림 상태 제어하기 (Control open state)
default-open prop이나 v-model:open 디렉티브를 사용해 열림 상태를 제어할 수 있어요.
<script setup lang="ts">
const open = ref(false)
defineShortcuts({
o: () => open.value = !open.value
})
</script>
<template>
<UModal v-model:open="open">
<UButton label="Open" color="neutral" variant="subtle" />
<template #content>
<Placeholder class="h-48 m-4" />
</template>
</UModal>
</template>
[!NOTE]
이 예시에서는
defineShortcuts를 활용해O키를 누르면 Modal을 토글할 수 있어요.
[!TIP]
이렇게 하면 트리거를 Modal 밖으로 옮기거나 완전히 제거할 수 있어요.
프로그래매틱 사용 (Programmatic usage)
useOverlay 컴포저블을 사용해 Modal을 프로그래매틱하게 열 수 있어요.
[!WARNING]
OverlayProvider컴포넌트를 사용하는App컴포넌트로 앱을 감싸야 합니다.
먼저 프로그래매틱하게 열릴 모달 컴포넌트를 만드세요:
<script setup lang="ts">
defineProps<{
count: number
}>()
const emit = defineEmits<{ close: [boolean] }>()
</script>
<template>
<UModal :close="{ onClick: () => emit('close', false) }" :title="`This modal was opened programmatically ${count} times`">
<template #footer>
<div class="flex gap-2">
<UButton color="neutral" label="Dismiss" @click="emit('close', false)" />
<UButton label="Success" @click="emit('close', true)" />
</div>
</template>
</UModal>
</template>
[!NOTE]
여기서는 Modal이 닫히거나 해제될 때
close이벤트를 emit 해요.close이벤트를 통해 어떤 데이터든 emit 할 수 있고, 그 데이터가open()의 resolve 값이 됩니다. promise가 resolve 되려면 이벤트가 반드시 emit 되어야 해요.
그런 다음 앱에서 사용하세요:
<script setup lang="ts">
import { LazyModalExample } from '#components'
const count = ref(0)
const toast = useToast()
const overlay = useOverlay()
const modal = overlay.create(LazyModalExample)
async function open() {
const instance = modal.open({
count: count.value
})
const shouldIncrement = await instance.result
if (shouldIncrement) {
count.value++
toast.add({
title: `Success: ${shouldIncrement}`,
color: 'success',
id: 'modal-success'
})
// Update the count
modal.patch({
count: count.value
})
return
}
toast.add({
title: `Dismissed: ${shouldIncrement}`,
color: 'error',
id: 'modal-dismiss'
})
}
</script>
<template>
<UButton label="Open" color="neutral" variant="subtle" @click="open" />
</template>
[!TIP]
모달 컴포넌트 안에서
emit('close')를 호출해 모달을 닫을 수 있어요.
중첩 모달 (Nested modals)
모달 안에 모달을 중첩할 수 있어요.
<script setup lang="ts">
const first = ref(false)
const second = ref(false)
</script>
<template>
<UModal v-model:open="first" title="First modal" :ui="{ footer: 'justify-end' }">
<UButton color="neutral" variant="subtle" label="Open" />
<template #footer>
<UButton label="Close" color="neutral" variant="outline" @click="first = false" />
<UModal v-model:open="second" title="Second modal" :ui="{ footer: 'justify-end' }">
<UButton label="Open second" color="neutral" />
<template #footer>
<UButton label="Close" color="neutral" variant="outline" @click="second = false" />
</template>
</UModal>
</template>
</UModal>
</template>
footer 슬롯 사용하기 (With footer slot)
#footer 슬롯을 사용하면 Modal의 body 뒤에 콘텐츠를 추가할 수 있어요.
<script setup lang="ts">
const open = ref(false)
</script>
<template>
<UModal v-model:open="open" title="Modal with footer" description="This is useful when you want a form in a Modal." :ui="{ footer: 'justify-end' }">
<UButton label="Open" color="neutral" variant="subtle" />
<template #body>
<Placeholder class="h-48" />
</template>
<template #footer="{ close }">
<UButton label="Cancel" color="neutral" variant="outline" @click="close" />
<UButton label="Submit" color="neutral" />
</template>
</UModal>
</template>
커맨드 팔레트 사용하기 (With command palette)
Modal의 콘텐츠 안에 CommandPalette 컴포넌트를 사용할 수 있어요.
<script setup lang="ts">
const searchTerm = ref('')
const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
key: 'modal-command-palette-users',
params: { q: searchTerm },
transform: (data: { id: number, name: string, email: string }[]) => {
return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
},
immediate: false
})
const groups = computed(() => [{
id: 'users',
label: searchTerm.value ? `Users matching “${searchTerm.value}”...` : 'Users',
items: users.value || [],
ignoreFilter: true
}])
function onOpen() {
if (!users.value?.length) {
execute()
}
}
</script>
<template>
<UModal @update:open="onOpen">
<UButton
label="Search users..."
color="neutral"
variant="subtle"
icon="i-lucide-search"
/>
<template #content>
<UCommandPalette
v-model:search-term="searchTerm"
:loading="status === 'pending'"
:groups="groups"
placeholder="Search users..."
class="h-80"
/>
</template>
</UModal>
</template>
[!NOTE]
이 예시는
immediate: false와 함께useLazyFetch를 사용해 Modal이 열릴 때만 데이터를 가져와요.
API
Props
/**
* Props for the Modal component
*/
interface ModalProps {
title?: string | undefined;
description?: string | undefined;
/**
* The content of the modal.
*/
content?: Omit<DialogContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DialogContentImplEmits>> | undefined;
/**
* Render an overlay behind the modal.
* @default true
*/
overlay?: boolean | undefined;
/**
* When `true`, enables scrollable overlay mode where content scrolls within the overlay.
* @default false
*/
scrollable?: boolean | undefined;
/**
* Animate the modal when opening or closing.
* @default true
*/
transition?: boolean | undefined;
/**
* When `true`, the modal will take up the full screen.
* @default false
*/
fullscreen?: boolean | undefined;
/**
* Render the modal in a portal.
* @default true
*/
portal?: string | false | true | HTMLElement | undefined;
/**
* Display a close button to dismiss the modal.
* `{ size: 'md', color: 'neutral', variant: 'ghost' }`{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;
/**
* When `false`, the modal will not close when clicking outside or pressing escape.
* @default true
*/
dismissible?: boolean | undefined;
ui?: { overlay?: SlotClass; content?: SlotClass; header?: SlotClass; wrapper?: SlotClass; body?: SlotClass; footer?: SlotClass; title?: SlotClass; description?: SlotClass; close?: SlotClass; } | undefined;
/**
* The controlled open state of the dialog. Can be binded as `v-model:open`.
*/
open?: boolean | 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 modality of the dialog When set to `true`, <br>
* interaction with outside elements will be disabled and only dialog content will be visible to screen readers.
* @default true
*/
modal?: boolean | undefined;
/**
* When set to `false`, the dialog content will not be unmounted when closed, but instead hidden with CSS. <br>
* Useful for SEO or when you want to improve performance by not remounting the component on every open.
* @default true
*/
unmountOnHide?: boolean | undefined;
}
Slots
/**
* Slots for the Modal component
*/
interface ModalSlots {
default(): any;
content(): any;
header(): any;
title(): any;
description(): any;
actions(): any;
close(): any;
body(): any;
footer(): any;
}
Emits
/**
* Emitted events for the Modal component
*/
interface ModalEmits {
leave: (payload: []) => void;
after:leave: (payload: []) => void;
enter: (payload: []) => void;
after:enter: (payload: []) => void;
close:prevent: (payload: []) => void;
update:open: (payload: [value: boolean]) => void;
}
테마 (Theme)
export default defineAppConfig({
ui: {
modal: {
slots: {
overlay: 'fixed inset-0',
content: 'bg-default divide-y divide-default flex flex-col focus:outline-none',
header: 'flex items-center gap-1.5 p-4 sm:px-6 min-h-(--ui-header-height)',
wrapper: '',
body: 'flex-1 p-4 sm:p-6',
footer: 'flex items-center gap-1.5 p-4 sm:px-6',
title: 'text-highlighted font-semibold',
description: 'mt-1 text-muted text-sm',
close: 'absolute top-4 end-4'
},
variants: {
transition: {
true: {
overlay: 'data-[state=open]:animate-[fade-in_200ms_var(--ease-out)] data-[state=closed]:animate-[fade-out_200ms_var(--ease-out)]',
content: 'data-[state=open]:animate-[scale-in_200ms_var(--ease-out)] data-[state=closed]:animate-[scale-out_200ms_var(--ease-out)]'
}
},
fullscreen: {
true: {
content: 'inset-0'
},
false: {
content: 'w-[calc(100vw-2rem)] max-w-lg rounded-lg shadow-lg ring ring-default'
}
},
overlay: {
true: {
overlay: 'bg-elevated/75'
}
},
scrollable: {
true: {
overlay: 'overflow-y-auto',
content: 'relative'
},
false: {
content: 'fixed',
body: 'overflow-y-auto'
}
}
},
compoundVariants: [
{
scrollable: true,
fullscreen: false,
class: {
overlay: 'grid place-items-center p-4 sm:py-8'
}
},
{
scrollable: false,
fullscreen: false,
class: {
content: 'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 max-h-[calc(100dvh-2rem)] sm:max-h-[calc(100dvh-4rem)] overflow-hidden'
}
}
]
}
}
})