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 匯入。