본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

ContextMenu

원문 보기 위키 갱신

요소를 오른쪽 클릭하면 표시되는 동작(actions) 메뉴 컴포넌트예요. 아이템 배열로 다양한 항목, 중첩 메뉴, 체크박스, 색상 강조, 커스텀 슬롯까지 만들 수 있어요.

출처: Nuxt UI

본문

요소를 오른쪽 클릭할 때 표시되는 동작 메뉴예요.

사용법

ContextMenu의 기본(default) 슬롯에는 원하는 무엇이든 넣을 수 있고, 그 위에서 오른쪽 클릭하면 메뉴가 표시돼요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items = ref<ContextMenuItem[][]>([
  [
    {
      label: "Appearance",
      children: [
        {
          label: "System",
          icon: "i-lucide-monitor"
        },
        {
          label: "Light",
          icon: "i-lucide-sun"
        },
        {
          label: "Dark",
          icon: "i-lucide-moon"
        }
      ]
    }
  ],
  [
    {
      label: "Show Sidebar",
      kbds: [
        "meta",
        "s"
      ]
    },
    {
      label: "Show Toolbar",
      kbds: [
        "shift",
        "meta",
        "d"
      ]
    },
    {
      label: "Collapse Pinned Tabs",
      disabled: true
    }
  ],
  [
    {
      label: "Refresh the Page"
    },
    {
      label: "Clear Cookies and Refresh"
    },
    {
      label: "Clear Cache and Refresh"
    },
    {
      type: "separator"
    },
    {
      label: "Developer",
      children: [
        [
          {
            label: "View Source",
            kbds: [
              "meta",
              "shift",
              "u"
            ]
          },
          {
            label: "Developer Tools",
            kbds: [
              "option",
              "meta",
              "i"
            ]
          },
          {
            label: "Inspect Elements",
            kbds: [
              "option",
              "meta",
              "c"
            ]
          }
        ],
        [
          {
            label: "JavaScript Console",
            kbds: [
              "option",
              "meta",
              "j"
            ]
          }
        ]
      ]
    }
  ]
])
</script>

<template>
  <UContextMenu :items="items">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

아이템 (Items)

items prop을 다음 속성을 가진 객체 배열로 사용할 수 있어요:

Link 컴포넌트의 어떤 속성이든 전달할 수 있는데요, to, target 같은 것들이에요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items = ref<ContextMenuItem[][]>([
  [
    {
      label: "Appearance",
      children: [
        {
          label: "System",
          icon: "i-lucide-monitor"
        },
        {
          label: "Light",
          icon: "i-lucide-sun"
        },
        {
          label: "Dark",
          icon: "i-lucide-moon"
        }
      ]
    }
  ],
  [
    {
      label: "Show Sidebar",
      kbds: [
        "meta",
        "s"
      ]
    },
    {
      label: "Show Toolbar",
      kbds: [
        "shift",
        "meta",
        "d"
      ]
    },
    {
      label: "Collapse Pinned Tabs",
      disabled: true
    }
  ],
  [
    {
      label: "Refresh the Page"
    },
    {
      label: "Clear Cookies and Refresh"
    },
    {
      label: "Clear Cache and Refresh"
    },
    {
      type: "separator"
    },
    {
      label: "Developer",
      children: [
        [
          {
            label: "View Source",
            kbds: [
              "meta",
              "shift",
              "u"
            ]
          },
          {
            label: "Developer Tools",
            kbds: [
              "option",
              "meta",
              "i"
            ]
          },
          {
            label: "Inspect Elements",
            kbds: [
              "option",
              "meta",
              "c"
            ]
          }
        ],
        [
          {
            label: "JavaScript Console",
            kbds: [
              "option",
              "meta",
              "j"
            ]
          }
        ]
      ]
    }
  ]
])
</script>

<template>
  <UContextMenu :items="items" :ui="{
  content: 'w-48'
}">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

[!NOTE]

You can also pass an array of arrays to the items prop to create separated groups of items.

items prop에 배열의 배열을 전달해서 분리된 그룹으로 나눠진 아이템들을 만들 수도 있어요.

[!TIP]

Each item can take a children array of objects with the same properties as the items prop to create a nested menu which can be controlled using the open, defaultOpen and content properties.

각 아이템은 open, defaultOpen, content 속성으로 제어할 수 있는 중첩 메뉴를 만들기 위해 items prop과 같은 속성들을 가진 객체의 children 배열을 가질 수 있어요.

크기 (Size)

size prop으로 ContextMenu의 크기를 바꿀 수 있어요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items = ref<ContextMenuItem[]>([
  {
    label: "System",
    icon: "i-lucide-monitor"
  },
  {
    label: "Light",
    icon: "i-lucide-sun"
  },
  {
    label: "Dark",
    icon: "i-lucide-moon"
  }
])
</script>

<template>
  <UContextMenu size="xl" :items="items" :ui="{
  content: 'w-48'
}">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

모달 (Modal)

modal prop으로 ContextMenu가 바깥 콘텐츠와의 상호작용을 막을지 제어할 수 있어요. 기본값은 true예요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items = ref<ContextMenuItem[]>([
  {
    label: "System",
    icon: "i-lucide-monitor"
  },
  {
    label: "Light",
    icon: "i-lucide-sun"
  },
  {
    label: "Dark",
    icon: "i-lucide-moon"
  }
])
</script>

<template>
  <UContextMenu :modal="false" :items="items" :ui="{
  content: 'w-48'
}">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

비활성화 (Disabled)

disabled prop으로 ContextMenu를 비활성화할 수 있어요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items = ref<ContextMenuItem[]>([
  {
    label: "System",
    icon: "i-lucide-monitor"
  },
  {
    label: "Light",
    icon: "i-lucide-sun"
  },
  {
    label: "Dark",
    icon: "i-lucide-moon"
  }
])
</script>

<template>
  <UContextMenu disabled :items="items" :ui="{
  content: 'w-48'
}">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

예시 (Examples)

체크박스 아이템으로 (With checkbox items)

type 속성을 checkbox로 설정하고 checked / onUpdateChecked 속성으로 아이템의 체크 상태를 제어할 수 있어요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const showSidebar = ref(true)
const showToolbar = ref(false)

const items = computed<ContextMenuItem[]>(() => [{
  label: 'View',
  type: 'label' as const
}, {
  type: 'separator' as const
}, {
  label: 'Show Sidebar',
  type: 'checkbox' as const,
  checked: showSidebar.value,
  onUpdateChecked(checked: boolean) {
    showSidebar.value = checked
  },
  onSelect(e: Event) {
    e.preventDefault()
  }
}, {
  label: 'Show Toolbar',
  type: 'checkbox' as const,
  checked: showToolbar.value,
  onUpdateChecked(checked: boolean) {
    showToolbar.value = checked
  }
}, {
  label: 'Collapse Pinned Tabs',
  type: 'checkbox' as const,
  disabled: true
}])
</script>

<template>
  <UContextMenu :items="items" :ui="{ content: 'w-48' }">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

[!NOTE]

To ensure reactivity for the checked state of items, it's recommended to wrap your items array inside a computed.

아이템의 checked 상태에 반응성을 보장하려면 items 배열을 computed 안에 감싸는 걸 권장해요.

색상 아이템으로 (With color items)

color 속성으로 특정 아이템을 색상으로 강조할 수 있어요.

<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const items: ContextMenuItem[][] = [
  [
    {
      label: 'View',
      icon: 'i-lucide-eye'
    },
    {
      label: 'Copy',
      icon: 'i-lucide-copy'
    },
    {
      label: 'Edit',
      icon: 'i-lucide-pencil'
    }
  ],
  [
    {
      label: 'Delete',
      color: 'error' as const,
      icon: 'i-lucide-trash'
    }
  ]
]
</script>

<template>
  <UContextMenu :items="items" :ui="{ content: 'w-48' }">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>
  </UContextMenu>
</template>

커스텀 슬롯으로 (With custom slot)

slot 속성으로 특정 아이템을 커스터마이징할 수 있어요.

다음 슬롯들에 접근할 수 있어요:

  • #{{ item.slot }}
  • #{{ item.slot }}-leading
  • #{{ item.slot }}-label
  • #{{ item.slot }}-trailing
<script setup lang="ts">
import type { ContextMenuItem } from '@nuxt/ui'

const loading = ref(true)

const items = [
  {
    label: 'Refresh the Page',
    slot: 'refresh' as const
  },
  {
    label: 'Clear Cookies and Refresh'
  },
  {
    label: 'Clear Cache and Refresh'
  }
] satisfies ContextMenuItem[]
</script>

<template>
  <UContextMenu :items="items" :ui="{ content: 'w-48' }">
    <div class="flex items-center justify-center rounded-md border border-dashed border-accented text-sm aspect-video w-72">
      Right click here
    </div>

    <template #refresh-label>
      {{ loading ? 'Refreshing...' : 'Refresh the Page' }}
    </template>

    <template #refresh-trailing>
      <UIcon v-if="loading" name="i-lucide-loader-circle" class="shrink-0 size-5 text-primary animate-spin" />
    </template>
  </UContextMenu>
</template>

[!TIP] See: #slots

You can also use the #item, #item-leading, #item-label and #item-trailing slots to customize all items.

#item, #item-leading, #item-label, #item-trailing 슬롯을 사용해서 모든 아이템을 한 번에 커스터마이징할 수도 있어요.

단축키 추출 (Extract shortcuts)

extractShortcuts 유틸리티로 kbds 속성을 가진 메뉴 아이템에서 자동으로 단축키를 정의할 수 있어요. 이 유틸리티는 단축키를 재귀적으로 추출해서 defineShortcuts와 호환되는 객체를 반환해요.

<script setup lang="ts">
const items = [
  [{
    label: 'Show Sidebar',
    kbds: ['meta', 'S'],
    onSelect() {
      console.log('Show Sidebar clicked')
    }
  }, {
    label: 'Show Toolbar',
    kbds: ['shift', 'meta', 'D'],
    onSelect() {
      console.log('Show Toolbar clicked')
    }
  }, {
    label: 'Collapse Pinned Tabs',
    disabled: true
  }], [{
    label: 'Refresh the Page'
  }, {
    label: 'Clear Cookies and Refresh'
  }, {
    label: 'Clear Cache and Refresh'
  }, {
    type: 'separator' as const
  }, {
    label: 'Developer',
    children: [[{
      label: 'View Source',
      kbds: ['option', 'meta', 'U'],
      onSelect() {
        console.log('View Source clicked')
      }
    }, {
      label: 'Developer Tools',
      kbds: ['option', 'meta', 'I'],
      onSelect() {
        console.log('Developer Tools clicked')
      }
    }], [{
      label: 'Inspect Elements',
      kbds: ['option', 'meta', 'C'],
      onSelect() {
        console.log('Inspect Elements clicked')
      }
    }], [{
      label: 'JavaScript Console',
      kbds: ['option', 'meta', 'J'],
      onSelect() {
        console.log('JavaScript Console clicked')
      }
    }]]
  }]
]

defineShortcuts(extractShortcuts(items))
</script>

[!NOTE]

In this example, Meta S, Shift Meta D, Option Meta U, Option Meta I, Option Meta C and Option Meta J would trigger the select function of the corresponding item.

이 예시에서 Meta S, Shift Meta D, Option Meta U, Option Meta I, Option Meta C, Option Meta J가 해당 아이템의 select 함수를 실행해요.

API

Props

/**
 * Props for the ContextMenu component
 */
interface ContextMenuProps {
  /**
   * @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.
   */
  content?: Omit<ContextMenuContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<MenuContentEmits>> | 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;
  disabled?: boolean | undefined;
  ui?: { content?: SlotClass; viewport?: 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 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;
  /**
   * The duration from when the trigger is pressed until the menu opens.
   * @default 700
   */
  pressOpenDelay?: number | undefined;
}

Slots

/**
 * Slots for the ContextMenu component
 */
interface ContextMenuSlots {
  default(): any;
  item(): any;
  item-leading(): any;
  item-label(): any;
  item-description(): any;
  item-trailing(): any;
  content-top(): any;
  content-bottom(): any;
}

Emits

/**
 * Emitted events for the ContextMenu component
 */
interface ContextMenuEmits {
  update:open: (payload: [payload: boolean]) => void;
}

테마 (Theme)

export default defineAppConfig({
  ui: {
    contextMenu: {
      slots: {
        content: 'min-w-32 max-h-(--reka-context-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-context-menu-content-transform-origin) flex flex-col',
        viewport: 'relative divide-y divide-default scroll-py-1 overflow-y-auto flex-1',
        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',
            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',
            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',
            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',
            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',
            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'
      }
    }
  }
})

변경 이력 (Changelog)

컴포넌트와 테마의 커밋 히스토리를 참고하세요.


더 알아보기 (Learn more)