드롭다운 메뉴
드롭다운 메뉴 (DropdownMenu)
요소를 클릭했을 때 동작을 표시하는 메뉴 컴포넌트예요. 중첩 메뉴, 체크박스/스위치 항목, 필터, 커스텀 슬롯 등 다양한 기능을 지원합니다.
출처: Nuxt UI
본문
요소를 클릭했을 때 동작을 표시하는 메뉴예요.
사용 방법 (Usage)
DropdownMenu의 기본 슬롯에 Button이나 다른 어떤 컴포넌트든 넣어 사용할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[][]>([
[
{
label: "Benjamin",
avatar: {
src: "https://github.com/benjamincanac.png",
loading: "lazy"
},
type: "label"
}
],
[
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog",
kbds: [
","
]
},
{
label: "Keyboard shortcuts",
icon: "i-lucide-monitor"
}
],
[
{
label: "Team",
icon: "i-lucide-users",
filter: {
placeholder: "Search members..."
},
children: [
[
{
label: "benjamincanac",
avatar: {
src: "https://github.com/benjamincanac.png",
loading: "lazy"
}
},
{
label: "HugoRCD",
avatar: {
src: "https://github.com/HugoRCD.png",
loading: "lazy"
}
},
{
label: "atinux",
avatar: {
src: "https://github.com/atinux.png",
loading: "lazy"
}
},
{
label: "romhml",
avatar: {
src: "https://github.com/romhml.png",
loading: "lazy"
}
},
{
label: "sandros94",
avatar: {
src: "https://github.com/sandros94.png",
loading: "lazy"
}
},
{
label: "J-Michalek",
avatar: {
src: "https://github.com/J-Michalek.png",
loading: "lazy"
}
},
{
label: "hywax",
avatar: {
src: "https://github.com/hywax.png",
loading: "lazy"
}
}
]
]
},
{
label: "Invite users",
icon: "i-lucide-user-plus",
children: [
[
{
label: "Email",
icon: "i-lucide-mail"
},
{
label: "Message",
icon: "i-lucide-message-square"
}
],
[
{
label: "More",
icon: "i-lucide-circle-plus",
children: [
{
label: "Import from Slack",
icon: "i-simple-icons-slack",
to: "https://slack.com",
target: "_blank"
},
{
label: "Import from Trello",
icon: "i-simple-icons-trello"
},
{
label: "Import from Asana",
icon: "i-simple-icons-asana"
}
]
}
]
]
},
{
label: "New team",
icon: "i-lucide-plus",
kbds: [
"meta",
"n"
]
}
],
[
{
label: "GitHub",
icon: "i-simple-icons-github",
to: "https://github.com/nuxt/ui",
target: "_blank"
},
{
label: "Support",
icon: "i-lucide-life-buoy",
to: "/docs/components/dropdown-menu"
},
{
label: "API",
icon: "i-lucide-cloud",
disabled: true
}
],
[
{
label: "Logout",
icon: "i-lucide-log-out",
color: "error",
kbds: [
"shift",
"meta",
"q"
]
}
]
])
</script>
<template>
<UDropdownMenu :items="items">
<UButton icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
항목 (Items)
items prop을 다음 속성을 가진 객체 배열로 사용할 수 있어요:
label?: stringicon?: stringavatar?: AvatarPropskbds?: string[] | KbdProps[]type?: "link" | "label" | "separator" | "checkbox"color?: "error" | "primary" | "secondary" | "success" | "info" | "warning" | "neutral"checked?: booleandisabled?: booleanslot?: stringonSelect?: (e: Event) => voidonUpdateChecked?: (checked: boolean) => voidchildren?: DropdownMenuItem[] | DropdownMenuItem[][]filter?: boolean | InputPropsfilterFields?: string[]ignoreFilter?: booleanclass?: anyui?: { item?: ClassNameValue, label?: ClassNameValue, separator?: ClassNameValue, itemLeadingIcon?: ClassNameValue, itemLeadingAvatarSize?: ClassNameValue, itemLeadingAvatar?: ClassNameValue, itemLabel?: ClassNameValue, itemLabelExternalIcon?: ClassNameValue, itemTrailing?: ClassNameValue, itemTrailingIcon?: ClassNameValue, itemTrailingKbds?: ClassNameValue, itemTrailingKbdsSize?: ClassNameValue }
Link 컴포넌트의 to, target 같은 어떤 속성이든 전달할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[][]>([
[
{
label: "Benjamin",
avatar: {
src: "https://github.com/benjamincanac.png",
loading: "lazy"
},
type: "label"
}
],
[
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog",
kbds: [
","
]
},
{
label: "Keyboard shortcuts",
icon: "i-lucide-monitor"
}
],
[
{
label: "Team",
icon: "i-lucide-users"
},
{
label: "Invite users",
icon: "i-lucide-user-plus",
children: [
[
{
label: "Email",
icon: "i-lucide-mail"
},
{
label: "Message",
icon: "i-lucide-message-square"
}
],
[
{
label: "More",
icon: "i-lucide-circle-plus",
children: [
{
label: "Import from Slack",
icon: "i-simple-icons-slack",
to: "https://slack.com",
target: "_blank"
},
{
label: "Import from Trello",
icon: "i-simple-icons-trello"
},
{
label: "Import from Asana",
icon: "i-simple-icons-asana"
}
]
}
]
]
},
{
label: "New team",
icon: "i-lucide-plus",
kbds: [
"meta",
"n"
]
}
],
[
{
label: "GitHub",
icon: "i-simple-icons-github",
to: "https://github.com/nuxt/ui",
target: "_blank"
},
{
label: "Support",
icon: "i-lucide-life-buoy",
to: "/docs/components/dropdown-menu"
},
{
label: "API",
icon: "i-lucide-cloud",
disabled: true
}
],
[
{
label: "Logout",
icon: "i-lucide-log-out",
kbds: [
"shift",
"meta",
"q"
]
}
]
])
</script>
<template>
<UDropdownMenu :items="items" :ui="{
content: 'w-48'
}">
<UButton icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
[!NOTE]
itemsprop에 배열의 배열을 전달해 구분된 항목 그룹을 만들 수도 있어요.
[!TIP]
각 항목에
itemsprop과 같은 속성을 가진 객체들의children배열을 넣으면 중첩 메뉴를 만들 수 있어요. 이때open,defaultOpen,content속성으로 제어할 수 있습니다.
콘텐츠 (Content)
content prop을 사용해 DropdownMenu 콘텐츠가 렌더링되는 방식을 제어할 수 있어요. 예를 들어 align이나 side 같은 옵션이 있습니다.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
}
])
</script>
<template>
<UDropdownMenu :items="items" :content="{
align: 'start',
side: 'bottom',
sideOffset: 8
}" :ui="{
content: 'w-48'
}">
<UButton label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
필터 (Filter) 4.6+
filter prop을 사용하면 DropdownMenu 안에 필터 입력을 표시할 수 있어요. 기본값은 false예요.
[!NOTE] See: #with-ignore-filter
ignore-filterprop을 사용하면 내부 검색을 끄고 직접 만든 검색 로직을 사용할 수 있어요.
[!NOTE] See: #with-filter-fields
filter-fieldsprop을 사용하면 필터링할 필드를 지정할 수 있어요. 기본적으로labelKeyprop을 사용합니다.
Input 컴포넌트의 어떤 속성이든 전달해 커스터마이즈할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
},
{
label: "Team",
icon: "i-lucide-users"
},
{
label: "Invite users",
icon: "i-lucide-user-plus"
},
{
label: "New team",
icon: "i-lucide-plus"
}
])
</script>
<template>
<UDropdownMenu :filter="{
icon: 'i-lucide-search'
}" :items="items" :content="{
align: 'start'
}" :ui="{
content: 'w-48'
}">
<UButton label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
[!TIP] See: #with-filter-items
children이 있는 항목의filter필드를 사용해 특정 하위 메뉴에서도 필터를 켤 수 있어요.
화살표 (Arrow)
arrow prop을 사용하면 DropdownMenu에 화살표를 표시할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
}
])
</script>
<template>
<UDropdownMenu arrow :items="items" :ui="{
content: 'w-48'
}">
<UButton label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
사이즈 (Size)
size prop을 사용하면 DropdownMenu의 크기를 제어할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
}
])
</script>
<template>
<UDropdownMenu size="xl" :items="items" :content="{
align: 'start'
}" :ui="{
content: 'w-48'
}">
<UButton size="xl" label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
[!WARNING]
sizeprop은 Button에 전달되지 않으니 직접 설정해야 해요.
[!NOTE]
같은 크기를 사용하면 DropdownMenu 항목이 Button과 완벽하게 정렬됩니다.
모달 (Modal)
modal prop을 사용하면 DropdownMenu가 외부 콘텐츠와의 상호작용을 막는지 제어할 수 있어요. 기본값은 true예요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
}
])
</script>
<template>
<UDropdownMenu :modal="false" :items="items" :ui="{
content: 'w-48'
}">
<UButton label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
비활성화 (Disabled)
disabled prop을 사용하면 DropdownMenu를 비활성화할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = ref<DropdownMenuItem[]>([
{
label: "Profile",
icon: "i-lucide-user"
},
{
label: "Billing",
icon: "i-lucide-credit-card"
},
{
label: "Settings",
icon: "i-lucide-cog"
}
])
</script>
<template>
<UDropdownMenu disabled :items="items" :ui="{
content: 'w-48'
}">
<UButton label="Open" icon="i-lucide-menu" color="neutral" variant="outline" />
</UDropdownMenu>
</template>
예시 (Examples)
체크박스 항목 사용하기 (With checkbox items)
type 속성에 checkbox를 사용하고 checked/onUpdateChecked 속성으로 항목의 체크 상태를 제어할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const showBookmarks = ref(true)
const showHistory = ref(false)
const showDownloads = ref(false)
const items = computed(() => [{
label: 'Interface',
icon: 'i-lucide-app-window',
type: 'label' as const
}, {
type: 'separator' as const
}, {
label: 'Show Bookmarks',
icon: 'i-lucide-bookmark',
type: 'checkbox' as const,
checked: showBookmarks.value,
onUpdateChecked(checked: boolean) {
showBookmarks.value = checked
},
onSelect(e: Event) {
e.preventDefault()
}
}, {
label: 'Show History',
icon: 'i-lucide-clock',
type: 'checkbox' as const,
checked: showHistory.value,
onUpdateChecked(checked: boolean) {
showHistory.value = checked
}
}, {
label: 'Show Downloads',
icon: 'i-lucide-download',
type: 'checkbox' as const,
checked: showDownloads.value,
onUpdateChecked(checked: boolean) {
showDownloads.value = checked
}
}] satisfies DropdownMenuItem[])
</script>
<template>
<UDropdownMenu :items="items" :content="{ align: 'start' }" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
[!NOTE]
항목의
checked상태에 반응성을 보장하려면items배열을computed안에 감싸는 것이 좋아요.
색상 항목 사용하기 (With color items)
color 속성을 사용하면 특정 항목을 색상으로 강조할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items: DropdownMenuItem[][] = [
[
{
label: 'View',
icon: 'i-lucide-eye'
},
{
label: 'Copy',
icon: 'i-lucide-copy'
},
{
label: 'Edit',
icon: 'i-lucide-pencil'
}
],
[
{
label: 'Delete',
color: 'error',
icon: 'i-lucide-trash'
}
]
]
</script>
<template>
<UDropdownMenu :items="items" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
필터 항목 사용하기 (With filter items) 4.6+
children이 있는 항목의 filter 속성을 사용하면 하위 메뉴 안에 필터 입력을 표시할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items: DropdownMenuItem[][] = [[{
label: 'Profile',
icon: 'i-lucide-user'
}, {
label: 'Billing',
icon: 'i-lucide-credit-card'
}, {
label: 'Settings',
icon: 'i-lucide-cog'
}], [{
label: 'Team',
icon: 'i-lucide-users',
filter: {
placeholder: 'Search members...'
},
children: [
{
label: 'benjamincanac',
avatar: { src: 'https://github.com/benjamincanac.png', loading: 'lazy' as const }
},
{
label: 'HugoRCD',
avatar: { src: 'https://github.com/HugoRCD.png', loading: 'lazy' as const }
},
{
label: 'atinux',
avatar: { src: 'https://github.com/atinux.png', loading: 'lazy' as const }
},
{
label: 'romhml',
avatar: { src: 'https://github.com/romhml.png', loading: 'lazy' as const }
},
{
label: 'sandros94',
avatar: { src: 'https://github.com/sandros94.png', loading: 'lazy' as const }
},
{
label: 'J-Michalek',
avatar: { src: 'https://github.com/J-Michalek.png', loading: 'lazy' as const }
},
{
label: 'hywax',
avatar: { src: 'https://github.com/hywax.png', loading: 'lazy' as const }
}
]
}, {
label: 'Invite users',
icon: 'i-lucide-user-plus',
children: [{
label: 'Invite by email',
icon: 'i-lucide-mail'
}, {
label: 'Invite by link',
icon: 'i-lucide-link'
}, {
label: 'Invite by SMS',
icon: 'i-lucide-message-square'
}, {
label: 'Invite by WhatsApp',
icon: 'i-simple-icons-whatsapp'
}]
}, {
label: 'New team',
icon: 'i-lucide-plus'
}]]
</script>
<template>
<UDropdownMenu :items="items" :content="{ align: 'start' }" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
열림 상태 제어하기 (Control open state)
default-open prop이나 v-model:open 디렉티브를 사용해 열림 상태를 제어할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const open = ref(false)
defineShortcuts({
o: () => open.value = !open.value
})
const items: DropdownMenuItem[] = [
{
label: 'Profile',
icon: 'i-lucide-user'
}, {
label: 'Billing',
icon: 'i-lucide-credit-card'
}, {
label: 'Settings',
icon: 'i-lucide-cog'
}
]
</script>
<template>
<UDropdownMenu v-model:open="open" :items="items" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
[!NOTE]
이 예시에서는
defineShortcuts를 활용해O키를 누르면 DropdownMenu를 토글할 수 있어요.
커스텀 슬롯 사용하기 (With custom slot)
slot 속성을 사용하면 특정 항목을 커스터마이즈할 수 있어요.
다음 슬롯들을 사용할 수 있습니다:
#{{ item.slot }}#{{ item.slot }}-leading#{{ item.slot }}-label#{{ item.slot }}-trailing
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items = [
{
label: 'Profile',
icon: 'i-lucide-user',
slot: 'profile' as const
}, {
label: 'Billing',
icon: 'i-lucide-credit-card'
}, {
label: 'Settings',
icon: 'i-lucide-cog'
}
] satisfies DropdownMenuItem[]
</script>
<template>
<UDropdownMenu :items="items" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
<template #profile-trailing>
<UIcon name="i-lucide-badge-check" class="shrink-0 size-5 text-primary" />
</template>
</UDropdownMenu>
</template>
[!TIP] See: #slots
#item,#item-leading,#item-label,#item-trailing슬롯을 사용해 모든 항목을 커스터마이즈할 수도 있어요.
항목 안에 스위치 사용하기 (With switch in items)
slot 속성을 #{{ slot }}-trailing 슬롯과 함께 사용하면 항목 안에 Switch를 렌더링할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const showBookmarks = ref(true)
const showHistory = ref(false)
const showDownloads = ref(false)
const items = computed(() => [{
label: 'Show Bookmarks',
icon: 'i-lucide-bookmark',
slot: 'switch' as const,
checked: showBookmarks.value,
onSelect(e: Event) {
e.preventDefault()
showBookmarks.value = !showBookmarks.value
}
}, {
label: 'Show History',
icon: 'i-lucide-clock',
slot: 'switch' as const,
checked: showHistory.value,
onSelect(e: Event) {
e.preventDefault()
showHistory.value = !showHistory.value
}
}, {
label: 'Show Downloads',
icon: 'i-lucide-download',
slot: 'switch' as const,
checked: showDownloads.value,
onSelect(e: Event) {
e.preventDefault()
showDownloads.value = !showDownloads.value
}
}] satisfies DropdownMenuItem[])
</script>
<template>
<UDropdownMenu :items="items" :content="{ align: 'start' }" :ui="{ content: 'w-48' }">
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
<template #switch-trailing="{ item }">
<USwitch :model-value="item.checked" tabindex="-1" />
</template>
</UDropdownMenu>
</template>
필터 무시하기 (With ignore filter) 4.6+
filter prop이나 children이 있는 항목의 filter 필드를 사용할 때 ignore-filter prop을 true로 설정하면 내부 검색을 끄고 직접 만든 검색 로직을 사용할 수 있어요.
<script setup lang="ts">
import { refDebounced } from '@vueuse/core'
import type { DropdownMenuItem } from '@nuxt/ui'
const searchTerm = ref('')
const searchTermDebounced = refDebounced(searchTerm, 200)
const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
key: 'dropdown-menu-users-search',
params: { q: searchTermDebounced },
transform: (data: { id: number, name: string }[]) => {
return data?.map(user => ({
label: user.name,
avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const }
})) as DropdownMenuItem[]
},
immediate: false
})
function onOpen() {
if (!users.value?.length) {
execute()
}
}
</script>
<template>
<UDropdownMenu
v-model:search-term="searchTerm"
:items="users || []"
:filter="{
icon: 'i-lucide-search',
loading: status === 'pending'
}"
ignore-filter
:content="{ align: 'start' }"
:ui="{ content: 'w-48' }"
@update:open="onOpen"
>
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
[!NOTE]
이 예시는 API 호출을 디바운스하기 위해
refDebounced를 사용해요.immediate: false로 fetch를 지연시켜 메뉴가 열리기 전에는 요청이 발생하지 않습니다.
필터 필드 사용하기 (With filter fields) 4.6+
filter prop이나 children이 있는 항목의 filter 필드를 사용할 때 filter-fields prop에 필터링할 필드 배열을 설정할 수 있어요. 기본값은 [labelKey]예요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items: DropdownMenuItem[] = [{
label: 'Leanne Graham',
description: 'Sincere@april.biz'
}, {
label: 'Ervin Howell',
description: 'Shanna@melissa.tv'
}, {
label: 'Clementine Bauch',
description: 'Nathan@yesenia.net'
}, {
label: 'Patricia Lebsack',
description: 'Julianne.OConner@kory.org'
}, {
label: 'Chelsey Dietrich',
description: 'Lucio_Hettinger@annie.me'
}]
</script>
<template>
<UDropdownMenu
:items="items"
filter
:filter-fields="['label', 'description']"
:content="{ align: 'start' }"
:ui="{ content: 'w-64' }"
>
<UButton label="Open" color="neutral" variant="outline" icon="i-lucide-menu" />
</UDropdownMenu>
</template>
트리거 콘텐츠 너비 (With trigger content width)
ui.content 슬롯에 w-(--reka-dropdown-menu-trigger-width) 클래스를 추가하면 콘텐츠를 버튼의 전체 너비로 확장할 수 있어요.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items: DropdownMenuItem[][] = [
[
{
label: 'View',
icon: 'i-lucide-eye'
},
{
label: 'Copy',
icon: 'i-lucide-copy'
},
{
label: 'Edit',
icon: 'i-lucide-pencil'
}
],
[
{
label: 'Delete',
color: 'error',
icon: 'i-lucide-trash'
}
]
]
</script>
<template>
<UDropdownMenu :items="items" :ui="{ content: 'w-(--reka-dropdown-menu-trigger-width)' }">
<UButton
label="Open"
class="w-46"
color="neutral"
variant="outline"
block
trailing-icon="i-lucide-chevron-down"
/>
</UDropdownMenu>
</template>
[!TIP]
app.config.ts에서 콘텐츠 너비를 전역으로도 바꿀 수 있어요:export default defineAppConfig({ ui: { dropdownMenu: { slots: { content: 'w-(--reka-dropdown-menu-trigger-width)' } } } })
단축키 추출하기 (Extract shortcuts)
extractShortcuts 유틸리티를 사용하면 kbds 속성이 있는 메뉴 항목에서 단축키를 자동으로 정의할 수 있어요. 재귀적으로 단축키를 추출해 defineShortcuts과 호환되는 객체를 반환합니다.
<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
const items: DropdownMenuItem[] = [{
label: 'Invite users',
icon: 'i-lucide-user-plus',
children: [{
label: 'Invite by email',
icon: 'i-lucide-send-horizontal',
kbds: ['meta', 'e'],
onSelect() {
console.log('Invite by email clicked')
}
}, {
label: 'Invite by link',
icon: 'i-lucide-link',
kbds: ['meta', 'i'],
onSelect() {
console.log('Invite by link clicked')
}
}]
}, {
label: 'New team',
icon: 'i-lucide-plus',
kbds: ['meta', 'n'],
onSelect() {
console.log('New team clicked')
}
}]
defineShortcuts(extractShortcuts(items))
</script>
[!NOTE]
이 예시에서
MetaE,MetaI,MetaN을 누르면 해당 항목의select함수가 트리거됩니다.
API
Props
/**
* Props for the DropdownMenu component
*/
interface DropdownMenuProps {
/**
* @default 'md'
*/
size?: "sm" | "md" | "xs" | "lg" | "xl" | undefined;
items?: T | undefined;
/**
* The icon displayed when an item is checked.
* @default appConfig.ui.icons.check
*/
checkedIcon?: any;
/**
* The icon displayed when an item is loading.
* @default appConfig.ui.icons.loading
*/
loadingIcon?: any;
/**
* The icon displayed when the item is an external link.
* Set to `false` to hide the external icon.
* @default true
*/
externalIcon?: any;
/**
* The content of the menu.
* @default { side: 'bottom', sideOffset: 8, collisionPadding: 8 }
*/
content?: Omit<DropdownMenuContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<MenuContentEmits>> | undefined;
/**
* Display an arrow alongside the menu.
* `{ rounded: true }`{lang="ts-type"}
* @default false
*/
arrow?: boolean | Omit<DropdownMenuArrowProps, "as" | "asChild"> | undefined;
/**
* Render the menu in a portal.
* @default true
*/
portal?: string | false | true | HTMLElement | undefined;
/**
* The key used to get the label from the item.
* @default 'label'
*/
labelKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
/**
* The key used to get the description from the item.
* @default 'description'
*/
descriptionKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
/**
* Whether to display a filter input or not.
* Can be an object to pass additional props to the input.
* `{ placeholder: 'Search...', variant: 'none' }`{lang="ts-type"}
* @default false
*/
filter?: boolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue"> | undefined;
/**
* The fields to filter by.
* @default [labelKey]
*/
filterFields?: string[] | undefined;
/**
* When `true`, items will not be filtered which is useful for custom filtering.
* @default false
*/
ignoreFilter?: boolean | undefined;
disabled?: boolean | undefined;
ui?: { content?: SlotClass; input?: SlotClass; empty?: SlotClass; viewport?: SlotClass; arrow?: SlotClass; group?: SlotClass; label?: SlotClass; separator?: SlotClass; item?: SlotClass; itemLeadingIcon?: SlotClass; itemLeadingAvatar?: SlotClass; itemLeadingAvatarSize?: SlotClass; itemTrailing?: SlotClass; itemTrailingIcon?: SlotClass; itemTrailingKbds?: SlotClass; itemTrailingKbdsSize?: SlotClass; itemWrapper?: SlotClass; itemLabel?: SlotClass; itemDescription?: SlotClass; itemLabelExternalIcon?: SlotClass; } | undefined;
/**
* The open state of the dropdown menu 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 menu. Can be used as `v-model:open`.
*/
open?: boolean | undefined;
/**
* The modality of the dropdown menu.
*
* When set to `true`, interaction with outside elements will be disabled and only menu content will be visible to screen readers.
* @default true
*/
modal?: boolean | undefined;
/**
* @default ''
*/
searchTerm?: string | undefined;
}
Slots
/**
* Slots for the DropdownMenu component
*/
interface DropdownMenuSlots {
default(): any;
item(): any;
item-leading(): any;
item-label(): any;
item-description(): any;
item-trailing(): any;
empty(): any;
content-top(): any;
content-bottom(): any;
}
Emits
/**
* Emitted events for the DropdownMenu component
*/
interface DropdownMenuEmits {
update:open: (payload: [payload: boolean]) => void;
update:searchTerm: (payload: [value: string]) => void;
}
테마 (Theme)
export default defineAppConfig({
ui: {
dropdownMenu: {
slots: {
content: 'min-w-32 max-h-(--reka-dropdown-menu-content-available-height) bg-default shadow-lg rounded-md ring ring-default overflow-hidden data-[state=open]:animate-[scale-in_100ms_var(--ease-out)] data-[state=closed]:animate-[scale-out_100ms_var(--ease-out)] origin-(--reka-dropdown-menu-content-transform-origin) flex flex-col',
input: 'border-b border-default',
empty: 'text-center text-muted',
viewport: 'relative divide-y divide-default scroll-py-1 overflow-y-auto flex-1',
arrow: 'fill-bg stroke-default',
group: 'p-1 isolate',
label: 'w-full flex items-center font-semibold text-highlighted',
separator: '-mx-1 my-1 h-px bg-border',
item: 'group relative w-full flex items-start select-none outline-none before:absolute before:z-[-1] before:inset-px before:rounded-md data-disabled:cursor-not-allowed data-disabled:opacity-75',
itemLeadingIcon: 'shrink-0',
itemLeadingAvatar: 'shrink-0',
itemLeadingAvatarSize: '',
itemTrailing: 'ms-auto inline-flex gap-1.5 items-center',
itemTrailingIcon: 'shrink-0',
itemTrailingKbds: 'hidden lg:inline-flex items-center shrink-0',
itemTrailingKbdsSize: '',
itemWrapper: 'flex-1 flex flex-col text-start min-w-0',
itemLabel: 'truncate',
itemDescription: 'truncate text-muted',
itemLabelExternalIcon: 'inline-block size-3 align-top text-dimmed'
},
variants: {
color: {
primary: '',
secondary: '',
success: '',
info: '',
warning: '',
error: '',
neutral: ''
},
active: {
true: {
item: 'text-highlighted before:bg-elevated',
itemLeadingIcon: 'text-default'
},
false: {
item: [
'text-default data-highlighted:text-highlighted data-[state=open]:text-highlighted data-highlighted:before:bg-elevated/50 data-[state=open]:before:bg-elevated/50',
'transition-colors before:transition-colors'
],
itemLeadingIcon: [
'text-dimmed group-data-highlighted:text-default group-data-[state=open]:text-default',
'transition-colors'
]
}
},
loading: {
true: {
itemLeadingIcon: 'animate-spin'
}
},
size: {
xs: {
label: 'p-1 text-xs gap-1',
item: 'p-1 text-xs gap-1',
empty: 'p-2 text-xs',
itemLeadingIcon: 'size-4',
itemLeadingAvatarSize: '3xs',
itemTrailingIcon: 'size-4',
itemTrailingKbds: 'gap-0.5',
itemTrailingKbdsSize: 'sm'
},
sm: {
label: 'p-1.5 text-xs gap-1.5',
item: 'p-1.5 text-xs gap-1.5',
empty: 'p-2.5 text-xs',
itemLeadingIcon: 'size-4',
itemLeadingAvatarSize: '3xs',
itemTrailingIcon: 'size-4',
itemTrailingKbds: 'gap-0.5',
itemTrailingKbdsSize: 'sm'
},
md: {
label: 'p-1.5 text-sm gap-1.5',
item: 'p-1.5 text-sm gap-1.5',
empty: 'p-2.5 text-sm',
itemLeadingIcon: 'size-5',
itemLeadingAvatarSize: '2xs',
itemTrailingIcon: 'size-5',
itemTrailingKbds: 'gap-0.5',
itemTrailingKbdsSize: 'md'
},
lg: {
label: 'p-2 text-sm gap-2',
item: 'p-2 text-sm gap-2',
empty: 'p-3 text-sm',
itemLeadingIcon: 'size-5',
itemLeadingAvatarSize: '2xs',
itemTrailingIcon: 'size-5',
itemTrailingKbds: 'gap-1',
itemTrailingKbdsSize: 'md'
},
xl: {
label: 'p-2 text-base gap-2',
item: 'p-2 text-base gap-2',
empty: 'p-3 text-base',
itemLeadingIcon: 'size-6',
itemLeadingAvatarSize: 'xs',
itemTrailingIcon: 'size-6',
itemTrailingKbds: 'gap-1',
itemTrailingKbdsSize: 'lg'
}
}
},
compoundVariants: [
{
color: 'primary',
active: false,
class: {
item: 'text-primary data-highlighted:text-primary data-highlighted:before:bg-primary/10 data-[state=open]:before:bg-primary/10',
itemLeadingIcon: 'text-primary/75 group-data-highlighted:text-primary group-data-[state=open]:text-primary'
}
},
{
color: 'secondary',
active: false,
class: {
item: 'text-secondary data-highlighted:text-secondary data-highlighted:before:bg-secondary/10 data-[state=open]:before:bg-secondary/10',
itemLeadingIcon: 'text-secondary/75 group-data-highlighted:text-secondary group-data-[state=open]:text-secondary'
}
},
{
color: 'success',
active: false,
class: {
item: 'text-success data-highlighted:text-success data-highlighted:before:bg-success/10 data-[state=open]:before:bg-success/10',
itemLeadingIcon: 'text-success/75 group-data-highlighted:text-success group-data-[state=open]:text-success'
}
},
{
color: 'info',
active: false,
class: {
item: 'text-info data-highlighted:text-info data-highlighted:before:bg-info/10 data-[state=open]:before:bg-info/10',
itemLeadingIcon: 'text-info/75 group-data-highlighted:text-info group-data-[state=open]:text-info'
}
},
{
color: 'warning',
active: false,
class: {
item: 'text-warning data-highlighted:text-warning data-highlighted:before:bg-warning/10 data-[state=open]:before:bg-warning/10',
itemLeadingIcon: 'text-warning/75 group-data-highlighted:text-warning group-data-[state=open]:text-warning'
}
},
{
color: 'error',
active: false,
class: {
item: 'text-error data-highlighted:text-error data-highlighted:before:bg-error/10 data-[state=open]:before:bg-error/10',
itemLeadingIcon: 'text-error/75 group-data-highlighted:text-error group-data-[state=open]:text-error'
}
},
{
color: 'primary',
active: true,
class: {
item: 'text-primary before:bg-primary/10',
itemLeadingIcon: 'text-primary'
}
},
{
color: 'secondary',
active: true,
class: {
item: 'text-secondary before:bg-secondary/10',
itemLeadingIcon: 'text-secondary'
}
},
{
color: 'success',
active: true,
class: {
item: 'text-success before:bg-success/10',
itemLeadingIcon: 'text-success'
}
},
{
color: 'info',
active: true,
class: {
item: 'text-info before:bg-info/10',
itemLeadingIcon: 'text-info'
}
},
{
color: 'warning',
active: true,
class: {
item: 'text-warning before:bg-warning/10',
itemLeadingIcon: 'text-warning'
}
},
{
color: 'error',
active: true,
class: {
item: 'text-error before:bg-error/10',
itemLeadingIcon: 'text-error'
}
}
],
defaultVariants: {
size: 'md'
}
}
}
})