ContextMenu
A shared menu opened by mouse, keyboard, or viewport coordinates, with scoped data and nested submenus.
Import
import { HuiContextMenu, HuiDropdownItem, HuiDropdownSubMenu } from '@nscode/handy-ui'
import type { ContextMenuExpose, ContextMenuPoint } from '@nscode/handy-ui'
Examples
Basic Usage
Call open from a region's contextmenu event. Selecting an item closes the menu by default. Focusable regions also support the menu key or Shift+F10 through the same event.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiContextMenu, HuiDropdownItem, HuiMessage } from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand } from '@nscode/handy-ui'
const menu = ref<ContextMenuExpose>()
const handleCommand = (command: DropdownCommand) => HuiMessage.info(`Action: ${command}`)
</script>
<template>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
Project files
</div>
<HuiContextMenu ref="menu" @command="handleCommand">
<HuiDropdownItem command="Copy" icon="copy">Copy</HuiDropdownItem>
<HuiDropdownItem command="Paste">Paste</HuiDropdownItem>
<HuiDropdownItem command="Refresh" icon="refresh" divided>Refresh</HuiDropdownItem>
</HuiContextMenu>
</template>
Shared Menu and Scoped Data
The second argument to open is passed to the default slot and the command event. Calling open again updates the position and data and collapses submenus.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiContextMenu, HuiDropdownItem, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand } from '@nscode/handy-ui'
interface ProjectFile {
name: string
locked: boolean
}
const menu = ref<ContextMenuExpose>()
const files: ProjectFile[] = [
{ name: 'Design files', locked: false },
{ name: 'Archived files', locked: true }
]
const file = (data: unknown) => data as ProjectFile | undefined
const handleCommand = (command: DropdownCommand, data: unknown) =>
HuiMessage.info(`${file(data)?.name}: ${command}`)
</script>
<template>
<HuiSpace wrap>
<div
v-for="item in files"
:key="item.name"
tabindex="0"
style="padding: 20px; border: 1px solid var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event, item)"
>
{{ item.name }}
</div>
</HuiSpace>
<HuiContextMenu ref="menu" @command="handleCommand">
<template #default="{ data }">
<HuiDropdownItem command="Open" icon="folder">Open {{ file(data)?.name }}</HuiDropdownItem>
<HuiDropdownItem command="Rename" icon="edit" :disabled="file(data)?.locked">
Rename
</HuiDropdownItem>
</template>
</HuiContextMenu>
</template>
Nested Submenus
Submenus inherit the root menu size and command handler. Escape closes one level at a time; the arrow keys enter or leave a submenu.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiContextMenu, HuiDropdownItem, HuiDropdownSubMenu, HuiMessage } from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand } from '@nscode/handy-ui'
const menu = ref<ContextMenuExpose>()
const handleCommand = (command: DropdownCommand) => HuiMessage.info(`Selected: ${command}`)
</script>
<template>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
Product plan
</div>
<HuiContextMenu ref="menu" @command="handleCommand">
<HuiDropdownItem command="Open" icon="folder">Open</HuiDropdownItem>
<HuiDropdownSubMenu title="Move to" icon="folder">
<HuiDropdownItem command="Group A">Group A</HuiDropdownItem>
<HuiDropdownSubMenu title="Group B">
<HuiDropdownItem command="Group B / Drafts">Drafts</HuiDropdownItem>
<HuiDropdownItem command="Group B / Final">Final</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiDropdownSubMenu>
<HuiDropdownSubMenu title="Restricted group" disabled>
<HuiDropdownItem command="Unavailable">Unavailable</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiContextMenu>
</template>
Sizes and Global Configuration
size accepts large, default, or small. When omitted, it follows HuiConfigProvider.
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiConfigProvider,
HuiContextMenu,
HuiDropdownItem,
HuiDropdownSubMenu,
HuiRadio,
HuiRadioGroup,
HuiSpace
} from '@nscode/handy-ui'
import type { ContextMenuExpose } from '@nscode/handy-ui'
const size = ref<'large' | 'default' | 'small'>('default')
const menu = ref<ContextMenuExpose>()
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRadioGroup v-model="size">
<HuiRadio value="large">large</HuiRadio>
<HuiRadio value="default">default</HuiRadio>
<HuiRadio value="small">small</HuiRadio>
</HuiRadioGroup>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
{{ size }}
</div>
</HuiSpace>
<HuiConfigProvider :size="size">
<HuiContextMenu ref="menu">
<HuiDropdownItem command="Open">Open</HuiDropdownItem>
<HuiDropdownSubMenu title="Groups">
<HuiDropdownItem command="Project A">Project A</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiContextMenu>
</HuiConfigProvider>
</template>
Disabled and Keep Open
disabled closes an open menu and makes later open calls inactive. Set hide-on-click to false for repeated actions.
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiContextMenu,
HuiDropdownItem,
HuiSwitch,
HuiSpace,
HuiMessage
} from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand } from '@nscode/handy-ui'
const menu = ref<ContextMenuExpose>()
const disabled = ref(false)
const keepOpen = ref(false)
const count = ref(0)
const handleCommand = (command: DropdownCommand) => {
count.value++
HuiMessage.info(`Action: ${command}`)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<span>Disabled</span><HuiSwitch v-model="disabled" aria-label="Disable context menu" />
<span>Keep open</span
><HuiSwitch v-model="keepOpen" aria-label="Keep menu open after selecting" />
<span>{{ count }} actions</span>
</HuiSpace>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
Working directory
</div>
</HuiSpace>
<HuiContextMenu
ref="menu"
:disabled="disabled"
:hide-on-click="!keepOpen"
@command="handleCommand"
>
<HuiDropdownItem command="Copy" icon="copy">Copy</HuiDropdownItem>
<HuiDropdownItem command="Refresh" icon="refresh">Refresh</HuiDropdownItem>
</HuiContextMenu>
</template>
Coordinates, Methods, and Visibility
Coordinates are relative to the viewport. The menu adjusts to available space. visible is a read-only boolean on the component instance.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiContextMenu, HuiDropdownItem, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { ContextMenuExpose } from '@nscode/handy-ui'
const menu = ref<ContextMenuExpose>()
const changes = ref(0)
const onVisibleChange = () => changes.value++
</script>
<template>
<HuiSpace wrap>
<HuiButton icon="chevron-down" @click="menu?.open({ x: 180, y: 160 })">Open at point</HuiButton>
<HuiButton icon="close" :disabled="!menu?.visible" @click="menu?.close()">Close</HuiButton>
<span>{{ menu?.visible ? 'Open' : 'Closed' }}, {{ changes }} changes</span>
</HuiSpace>
<HuiContextMenu ref="menu" @visible-change="onVisibleChange">
<HuiDropdownItem command="Open">Open</HuiDropdownItem>
<HuiDropdownItem command="Copy">Copy</HuiDropdownItem>
</HuiContextMenu>
</template>
Popup Appearance
class, style, and other attributes are forwarded to the popup. popper-class adds a global style class.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiContextMenu, HuiDropdownItem } from '@nscode/handy-ui'
import type { ContextMenuExpose } from '@nscode/handy-ui'
const menu = ref<ContextMenuExpose>()
</script>
<template>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
Team files
</div>
<HuiContextMenu
ref="menu"
popper-class="context-demo-popup"
style="min-width: 220px"
data-menu="team"
>
<HuiDropdownItem command="Open">Open team files</HuiDropdownItem>
<HuiDropdownItem command="Copy">Copy directory address</HuiDropdownItem>
</HuiContextMenu>
</template>
<style>
.context-demo-popup {
border-color: var(--hui-color-primary);
}
</style>
Table Row Menu
row-contextmenu provides the row, column, and original event. row-dblclick handles double clicks separately. Edit and delete actions are disabled for locked rows; deletion requires confirmation.
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import {
HuiTable,
HuiContextMenu,
HuiDropdownItem,
HuiMessage,
HuiMessageBox
} from '@nscode/handy-ui'
import type {
ContextMenuExpose,
DropdownCommand,
TableColumnConfig,
TableRowData
} from '@nscode/handy-ui'
interface FileRow extends TableRowData {
id: number
name: string
locked: boolean
}
const menu = ref<ContextMenuExpose>()
const rows = ref<FileRow[]>([
{ id: 1, name: 'Design files', locked: false },
{ id: 2, name: 'Archived files', locked: true }
])
const columns: TableColumnConfig[] = [{ prop: 'name', label: 'File name' }]
// 等待期间集合或权限变化,使原记录操作失效。
const pending = ref(false)
let alive = true
let revision = 0
watch(rows, () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
const file = (data: unknown) => data as FileRow | undefined
const openRow = (row: TableRowData, _column: TableColumnConfig, event: MouseEvent) =>
menu.value?.open(event, row)
const onDoubleClick = (row: TableRowData) => HuiMessage.info(`Double-click: ${row.name}`)
const handleCommand = async (command: DropdownCommand, data: unknown) => {
const target = file(data)
if (!alive || pending.value || !target || target.locked) return
if (rows.value.find((row) => row.id === target.id) !== target) return
const request = revision
const collection = rows.value
const current = () =>
alive &&
request === revision &&
rows.value === collection &&
!target.locked &&
rows.value.find((row) => row.id === target.id) === target
pending.value = true
try {
if (command === 'edit') {
const { value = '' } = await HuiMessageBox.prompt(
`Enter a new name for "${target.name}"`,
'Edit record',
{
inputValidator: (value) => !!value.trim() || 'Enter a file name'
}
)
if (current()) target.name = value.trim()
} else if (command === 'delete') {
await HuiMessageBox.confirm(`Delete "${target.name}"?`, 'Confirm deletion', {
type: 'warning',
confirmButtonType: 'danger',
confirmButtonText: 'Delete'
})
if (current()) rows.value = rows.value.filter((row) => row !== target)
}
} catch {
return
} finally {
if (alive) pending.value = false
}
}
</script>
<template>
<HuiTable
:data="rows"
:columns="columns"
row-key="id"
@row-contextmenu="openRow"
@row-dblclick="onDoubleClick"
>
<template #name="{ row }"
><span tabindex="0">{{ row.name }}</span></template
>
</HuiTable>
<HuiContextMenu ref="menu" @command="handleCommand">
<template #default="{ data }">
<HuiDropdownItem command="edit" icon="edit" :disabled="pending || file(data)?.locked"
>Edit</HuiDropdownItem
>
<HuiDropdownItem command="delete" icon="trash" :disabled="pending || file(data)?.locked"
>Delete</HuiDropdownItem
>
</template>
</HuiContextMenu>
</template>
Tree Node Menu
node-contextmenu provides { node, key, event }, including for disabled nodes. This example adds children, renames nodes, and deletes a subtree after confirming its full size.
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { HuiTree, HuiContextMenu, HuiDropdownItem, HuiMessageBox } from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand, TreeNodeData } from '@nscode/handy-ui'
interface NodeTarget {
node: TreeNodeData
key: string | number
}
interface NodeLocation {
siblings: TreeNodeData[]
index: number
node: TreeNodeData
disabled: boolean
}
const menu = ref<ContextMenuExpose>()
const nodes = ref<TreeNodeData[]>([
{ id: 'team', label: 'Project files', children: [{ id: 'draft', label: 'Drafts' }] },
{ id: 'archive', label: 'Read-only archive', disabled: true }
])
const targetOf = (data: unknown) => data as NodeTarget | undefined
// 深层内容、祖先权限及同key替换都作废旧确认。
const pending = ref(false)
let alive = true
let revision = 0
watch(nodes, () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
function locate(
items: TreeNodeData[],
key: string | number,
parentDisabled = false
): NodeLocation | undefined {
for (let index = 0; index < items.length; index++) {
const node = items[index]
const disabled = parentDisabled || !!node.disabled
if (node.id === key) return { siblings: items, index, node, disabled }
const found = locate(node.children ?? [], key, disabled)
if (found) return found
}
}
const countNodes = (node: TreeNodeData): number =>
1 + (node.children ?? []).reduce((count, child) => count + countNodes(child), 0)
let serial = 0
const handleCommand = async (command: DropdownCommand, data: unknown) => {
const target = targetOf(data)
if (!alive || pending.value || !target || target.node.disabled) return
const { node, key } = target
const original = locate(nodes.value, key)
if (!original || original.node !== node || original.disabled) return
if (command === 'add') {
const next = ++serial
;(node.children ??= []).push({ id: `new-${next}`, label: `New node ${next}` })
return
}
const request = revision
const collection = nodes.value
const current = () => {
const location = locate(nodes.value, key)
return alive &&
request === revision &&
nodes.value === collection &&
location?.node === node &&
!location.disabled
? location
: undefined
}
pending.value = true
try {
if (command === 'rename') {
const { value = '' } = await HuiMessageBox.prompt(
`Enter a new name for "${node.label}"`,
'Rename',
{
inputValidator: (value) => !!value.trim() || 'Enter a node name'
}
)
const location = current()
if (location) location.node.label = value.trim()
} else if (command === 'delete') {
await HuiMessageBox.confirm(
`Delete "${node.label}" and its descendants (${countNodes(node)} nodes in total)?`,
'Confirm deletion',
{ type: 'warning', confirmButtonType: 'danger', confirmButtonText: 'Delete' }
)
const location = current()
if (location) location.siblings.splice(location.index, 1)
}
} catch {
return
} finally {
if (alive) pending.value = false
}
}
</script>
<template>
<HuiTree
:data="nodes"
default-expand-all
@node-contextmenu="({ node, key, event }) => menu?.open(event, { node, key })"
/>
<HuiContextMenu ref="menu" @command="handleCommand">
<template #default="{ data }">
<HuiDropdownItem
command="add"
icon="plus"
:disabled="pending || targetOf(data)?.node.disabled"
>Add child</HuiDropdownItem
>
<HuiDropdownItem
command="rename"
icon="edit"
:disabled="pending || targetOf(data)?.node.disabled"
>Rename</HuiDropdownItem
>
<HuiDropdownItem
command="delete"
icon="trash"
divided
:disabled="pending || targetOf(data)?.node.disabled"
>Delete</HuiDropdownItem
>
</template>
</HuiContextMenu>
</template>
Tab Menu
tab-contextmenu provides the pane and original event without switching the active tab. Refresh updates the example content. The four close actions directly update the tabs array.
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiTabs,
HuiTabPane,
HuiContextMenu,
HuiDropdownItem,
HuiButton,
HuiSpace,
HuiEmpty
} from '@nscode/handy-ui'
import type { ContextMenuExpose, DropdownCommand, TabPaneInstance } from '@nscode/handy-ui'
interface DemoTab {
name: string
label: string
refresh: number
}
type CloseCommand = 'close' | 'others' | 'right' | 'all'
const initial = (): DemoTab[] => [
{ name: 'overview', label: 'Overview', refresh: 0 },
{ name: 'files', label: 'Files', refresh: 0 },
{ name: 'members', label: 'Members', refresh: 0 }
]
const tabs = ref(initial())
const active = ref<string | number | undefined>('overview')
const menu = ref<ContextMenuExpose>()
const pane = (data: unknown) => data as TabPaneInstance | undefined
const targets = (command: CloseCommand, name?: string | number) => {
const index = tabs.value.findIndex((tab) => tab.name === name)
if (command !== 'all' && index < 0) return []
return tabs.value.filter(
(tab, position) =>
command === 'all' ||
(command === 'close'
? tab.name === name
: command === 'others'
? tab.name !== name
: position > index)
)
}
const handleCommand = (command: DropdownCommand, data: unknown) => {
const name = pane(data)?.name
if (command === 'refresh') {
const tab = tabs.value.find((tab) => tab.name === name)
if (tab) tab.refresh++
return
}
if (command !== 'close' && command !== 'others' && command !== 'right' && command !== 'all')
return
const removed = new Set(targets(command, name).map((tab) => tab.name))
tabs.value = tabs.value.filter((tab) => !removed.has(tab.name))
if (active.value !== undefined && removed.has(String(active.value)))
active.value = tabs.value[0]?.name
}
const reset = () => {
if (tabs.value.length) return
tabs.value = initial()
active.value = 'overview'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton icon="refresh" :disabled="tabs.length > 0" @click="reset"
>Restore example tabs</HuiButton
>
<HuiTabs
v-if="tabs.length"
v-model="active"
@tab-contextmenu="(tab, event) => menu?.open(event, tab)"
>
<HuiTabPane v-for="tab in tabs" :key="tab.name" :name="tab.name" :label="tab.label">
{{ tab.label }}, refreshed {{ tab.refresh }} times
</HuiTabPane>
</HuiTabs>
<HuiEmpty v-else description="No tabs" />
</HuiSpace>
<HuiContextMenu ref="menu" @command="handleCommand">
<template #default="{ data }">
<HuiDropdownItem command="refresh" icon="refresh">Refresh</HuiDropdownItem>
<HuiDropdownItem command="close" icon="close">Close</HuiDropdownItem>
<HuiDropdownItem command="others" :disabled="!targets('others', pane(data)?.name).length"
>Close others</HuiDropdownItem
>
<HuiDropdownItem command="right" :disabled="!targets('right', pane(data)?.name).length"
>Close to the right</HuiDropdownItem
>
<HuiDropdownItem command="all" divided>Close all</HuiDropdownItem>
</template>
</HuiContextMenu>
</template>
Props
| Prop | Description | Type | Default |
|---|---|---|---|
| size | Menu and submenu size; inherits global configuration when omitted | 'large' | 'default' | 'small' | 'default' |
| disabled | Closes the menu and prevents later open calls | boolean | false |
| hideOnClick | Close after selecting an item | boolean | true |
| popperClass | Additional popup class | string | undefined |
Events
| Event | Description | Parameters |
|---|---|---|
| command | An item in the root menu or a submenu is selected | (command: DropdownCommand, data: unknown) |
| visibleChange | Fires when opened or closed, but not when repositioned | (visible: boolean) |
Slots
| Slot | Description | Parameters |
|---|---|---|
| default | Items and submenus; do not wrap them in HuiDropdownMenu | { data: unknown } |
Methods
| Name | Description | Type |
|---|---|---|
| open | Open or reposition, replacing scoped data | (target: ContextMenuOpenTarget, data?: unknown) => void |
| close | Close the menu | () => void |
| visible | Current visibility, read-only | boolean |
Types
interface ContextMenuPoint {
x: number
y: number
}
type ContextMenuOpenTarget = MouseEvent | KeyboardEvent | ContextMenuPoint
interface ContextMenuExpose {
open: (target: ContextMenuOpenTarget, data?: unknown) => void
close: () => void
readonly visible: boolean
}
type DropdownCommand = string | number | undefined
Import ContextMenuProps, ContextMenuEmits, ContextMenuPoint, ContextMenuOpenTarget, and ContextMenuExpose from @nscode/handy-ui.