ContextMenu 右键菜单
同一个菜单可在多个位置打开,支持鼠标、键盘、视口坐标、作用域数据及多级子菜单。
引入
ts
import { HuiContextMenu, HuiDropdownItem, HuiDropdownSubMenu } from '@nscode/handy-ui'
import type { ContextMenuExpose, ContextMenuPoint } from '@nscode/handy-ui'
示例
基础用法
在区域的 contextmenu 事件中调用 open,点击菜单项后默认关闭。区域可聚焦时,菜单键或 Shift+F10 也会通过同一事件打开菜单。
vue
<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(`执行:${command}`)
</script>
<template>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
项目文件
</div>
<HuiContextMenu ref="menu" @command="handleCommand">
<HuiDropdownItem command="复制" icon="copy">复制</HuiDropdownItem>
<HuiDropdownItem command="粘贴">粘贴</HuiDropdownItem>
<HuiDropdownItem command="刷新" icon="refresh" divided>刷新</HuiDropdownItem>
</HuiContextMenu>
</template>
共享菜单与作用域数据
open 的第二个参数会传给默认插槽和 command 事件;菜单打开时再次调用 open 会更新位置与数据,并收起子菜单。
vue
<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: '设计稿', locked: false },
{ name: '已归档资料', 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="打开" icon="folder">打开 {{ file(data)?.name }}</HuiDropdownItem>
<HuiDropdownItem command="重命名" icon="edit" :disabled="file(data)?.locked">
重命名
</HuiDropdownItem>
</template>
</HuiContextMenu>
</template>
多级子菜单
子菜单沿用根菜单的尺寸与命令事件。Esc 逐层收起,左右键进入或退出子菜单。
vue
<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(`已选择:${command}`)
</script>
<template>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
产品方案
</div>
<HuiContextMenu ref="menu" @command="handleCommand">
<HuiDropdownItem command="打开" icon="folder">打开</HuiDropdownItem>
<HuiDropdownSubMenu title="移动到" icon="folder">
<HuiDropdownItem command="分组 A">分组 A</HuiDropdownItem>
<HuiDropdownSubMenu title="分组 B">
<HuiDropdownItem command="分组 B / 草稿">草稿</HuiDropdownItem>
<HuiDropdownItem command="分组 B / 定稿">定稿</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiDropdownSubMenu>
<HuiDropdownSubMenu title="无权限分组" disabled>
<HuiDropdownItem command="不可访问">不可访问</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiContextMenu>
</template>
尺寸与全局配置
size 支持 large、default、small;不写时跟随 HuiConfigProvider。
vue
<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="打开">打开</HuiDropdownItem>
<HuiDropdownSubMenu title="分组">
<HuiDropdownItem command="项目 A">项目 A</HuiDropdownItem>
</HuiDropdownSubMenu>
</HuiContextMenu>
</HuiConfigProvider>
</template>
禁用与选择后保留
disabled 会关闭已打开的菜单,并使后续 open 无效。hide-on-click="false" 允许连续选择多个命令。
vue
<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(`执行:${command}`)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<span>禁用</span><HuiSwitch v-model="disabled" aria-label="禁用右键菜单" />
<span>选择后保留</span><HuiSwitch v-model="keepOpen" aria-label="选择后保留菜单" />
<span>已执行 {{ count }} 次</span>
</HuiSpace>
<div
tabindex="0"
style="padding: 24px; border: 1px dashed var(--hui-border-color); border-radius: 4px"
@contextmenu="menu?.open($event)"
>
工作目录
</div>
</HuiSpace>
<HuiContextMenu
ref="menu"
:disabled="disabled"
:hide-on-click="!keepOpen"
@command="handleCommand"
>
<HuiDropdownItem command="复制" icon="copy">复制</HuiDropdownItem>
<HuiDropdownItem command="刷新" icon="refresh">刷新</HuiDropdownItem>
</HuiContextMenu>
</template>
坐标、方法与显示事件
坐标相对浏览器视口,超出可用空间时会自动调整。visible 是组件实例上只读的布尔值。
vue
<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 })">坐标打开</HuiButton>
<HuiButton icon="close" :disabled="!menu?.visible" @click="menu?.close()">关闭</HuiButton>
<span>状态:{{ menu?.visible ? '打开' : '关闭' }},变化 {{ changes }} 次</span>
</HuiSpace>
<HuiContextMenu ref="menu" @visible-change="onVisibleChange">
<HuiDropdownItem command="打开">打开</HuiDropdownItem>
<HuiDropdownItem command="复制">复制</HuiDropdownItem>
</HuiContextMenu>
</template>
浮层外观
class、style 和其他透传属性落在浮层上,popper-class 可添加全局样式类。
vue
<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)"
>
团队资料
</div>
<HuiContextMenu
ref="menu"
popper-class="context-demo-popup"
style="min-width: 220px"
data-menu="team"
>
<HuiDropdownItem command="打开">打开团队资料</HuiDropdownItem>
<HuiDropdownItem command="复制">复制目录地址</HuiDropdownItem>
</HuiContextMenu>
</template>
<style>
.context-demo-popup {
border-color: var(--hui-color-primary);
}
</style>
表格行菜单
row-contextmenu 提供行、列与原始事件,row-dblclick 可单独处理双击。锁定行的编辑、删除项禁用;删除前先确认。
vue
<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: '设计稿', locked: false },
{ id: 2, name: '归档资料', locked: true }
])
const columns: TableColumnConfig[] = [{ prop: 'name', label: '文件名' }]
// 菜单删除确认:表格。等待期间集合或权限变化,使旧操作失效。
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(`双击:${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(
`为“${target.name}”输入新名称`,
'编辑记录',
{
inputValidator: (value) => !!value.trim() || '请输入文件名'
}
)
if (current()) target.name = value.trim()
} else if (command === 'delete') {
await HuiMessageBox.confirm(`删除“${target.name}”?`, '删除确认', {
type: 'warning',
confirmButtonType: 'danger',
confirmButtonText: '删除'
})
if (current()) rows.value = rows.value.filter((row) => row !== target)
}
} catch {
// 取消、关闭或 Esc 均不修改数据。
} 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"
>编辑</HuiDropdownItem
>
<HuiDropdownItem command="delete" icon="trash" :disabled="pending || file(data)?.locked"
>删除</HuiDropdownItem
>
</template>
</HuiContextMenu>
</template>
树节点菜单
node-contextmenu 参数为 { node, key, event },禁用节点也会触发。示例可新增子节点、重命名与删除;删除前确认整棵目标子树的范围。
vue
<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: '项目资料', children: [{ id: 'draft', label: '草稿' }] },
{ id: 'archive', label: '只读归档', 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: `新节点 ${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(`为“${node.label}”输入新名称`, '重命名', {
inputValidator: (value) => !!value.trim() || '请输入节点名称'
})
const location = current()
if (location) location.node.label = value.trim()
} else if (command === 'delete') {
await HuiMessageBox.confirm(
`删除“${node.label}”及其子节点,共 ${countNodes(node)} 条数据?`,
'删除确认',
{ type: 'warning', confirmButtonType: 'danger', confirmButtonText: '删除' }
)
const location = current()
if (location) location.siblings.splice(location.index, 1)
}
} catch {
// 取消、关闭或 Esc 均不修改节点。
} 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"
>新增子节点</HuiDropdownItem
>
<HuiDropdownItem
command="rename"
icon="edit"
:disabled="pending || targetOf(data)?.node.disabled"
>重命名</HuiDropdownItem
>
<HuiDropdownItem
command="delete"
icon="trash"
divided
:disabled="pending || targetOf(data)?.node.disabled"
>删除</HuiDropdownItem
>
</template>
</HuiContextMenu>
</template>
多页签菜单
tab-contextmenu 提供页签信息与原始事件,不切换当前页。刷新更新示例内容,四种关闭直接修改页签数组。
vue
<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: '概览', refresh: 0 },
{ name: 'files', label: '文件', refresh: 0 },
{ name: 'members', label: '成员', 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">恢复示例页签</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 }},刷新 {{ tab.refresh }} 次
</HuiTabPane>
</HuiTabs>
<HuiEmpty v-else description="没有页签" />
</HuiSpace>
<HuiContextMenu ref="menu" @command="handleCommand">
<template #default="{ data }">
<HuiDropdownItem command="refresh" icon="refresh">刷新</HuiDropdownItem>
<HuiDropdownItem command="close" icon="close">关闭</HuiDropdownItem>
<HuiDropdownItem command="others" :disabled="!targets('others', pane(data)?.name).length"
>关闭其他</HuiDropdownItem
>
<HuiDropdownItem command="right" :disabled="!targets('right', pane(data)?.name).length"
>关闭右侧</HuiDropdownItem
>
<HuiDropdownItem command="all" divided>全部关闭</HuiDropdownItem>
</template>
</HuiContextMenu>
</template>
Props
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| size | 菜单及子菜单尺寸;不写时跟随全局配置 | 'large' | 'default' | 'small' | 'default' |
| disabled | 禁用;已打开时会关闭,之后 open 不响应 | boolean | false |
| hideOnClick | 选择菜单项后关闭 | boolean | true |
| popperClass | 浮层附加类名 | string | undefined |
Events
| 事件 | 说明 | 参数 |
|---|---|---|
| command | 选择根菜单或子菜单的菜单项 | (command: DropdownCommand, data: unknown) |
| visibleChange | 打开、关闭时触发;重新定位不触发 | (visible: boolean) |
Slots
| 插槽 | 说明 | 参数 |
|---|---|---|
| default | 菜单项与子菜单,不需要再包 HuiDropdownMenu | { data: unknown } |
方法
| 名称 | 说明 | 类型 |
|---|---|---|
| open | 打开或重新定位,并替换作用域数据 | (target: ContextMenuOpenTarget, data?: unknown) => void |
| close | 关闭菜单 | () => void |
| visible | 当前是否显示,只读 | boolean |
类型
ts
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
ContextMenuProps、ContextMenuEmits、ContextMenuPoint、ContextMenuOpenTarget、ContextMenuExpose 均可从 @nscode/handy-ui 导入。