多级菜单指令化
Directive
v-contextmenu="菜单数据"
参考一个开源项目 PPTIST
结果样式
目录结构
指令
菜单template 组件
引入
vue3 使用指令 要在main.js中引入
import Directive from '@/plugins/directive'
app.use(Directive)
一 · 指令目录结构 文件
contextmenu.ts
import { Directive, createVNode, render, DirectiveBinding } from 'vue'
import ContextmenuComponent from '@/components/Contextmenu/index.vue'
const CTX_CONTEXTMENU_HANDLER = 'CTX_CONTEXTMENU_HANDLER'
const contextmenuListener = (el: HTMLElement, event: MouseEvent, binding: DirectiveBinding) => {
event.stopPropagation()
event.preventDefault()
const menus = binding.value(el)
if (!menus) return
let container: HTMLDivElement | null = null
// 移除右键菜单并取消相关的事件监听
const removeContextmenu = () => {
if (container) {
document.body.removeChild(container)
container = null
}
el.classList.remove('contextmenu-active')
document.body.removeEventListener('scroll', removeContextmenu)
window.removeEventListener('resize', removeContextmenu)
}
// 创建自定义菜单
const options = {
axis: { x: event.x, y: event.y },
el,
menus,
removeContextmenu,
}
container = document.createElement('div')
const vm = createVNode(ContextmenuComponent, options, null)
render(vm, container)
document.body.appendChild(container)
// 为目标节点添加菜单激活状态的className
el.classList.add('contextmenu-active')
// 页面变化时移除菜单
document.body.addEventListener('scroll', removeContextmenu)
window.addEventListener('resize', removeContextmenu)
}
const ContextmenuDirective: Directive = {
mounted(el: HTMLElement, binding) {
el[CTX_CONTEXTMENU_HANDLER] = (event: MouseEvent) => contextmenuListener(el, event, binding)
el.addEventListener('contextmenu', el[CTX_CONTEXTMENU_HANDLER])
},
unmounted(el: HTMLElement) {
if (el && el[CTX_CONTEXTMENU_HANDLER]) {
el.removeEventListener('contextmenu', el[CTX_CONTEXTMENU_HANDLER])
delete el[CTX_CONTEXTMENU_HANDLER]
}
},
}
export default ContextmenuDirective
plugin directive index.ts
import { App } from 'vue'
import Contextmenu from './contextmenu'
import ClickOutside from './clickOutside'
export default {
install(app: App) {
app.directive('contextmenu', Contextmenu)
app.directive('click-outside', ClickOutside)
}
}
二· 菜单组件 单文件组件
MenuContent.vue
index.vue
type.ts
export interface ContextmenuItem {
text?: string;
subText?: string;
divider?: boolean;
disable?: boolean;
hide?: boolean;
children?: ContextmenuItem[];
handler?: (el: HTMLElement) => void;
}
export interface Axis {
x: number;
y: number;
}
三·用法
v-contextmenu="contextmenusThumbnails"
import { ContextmenuItem } from '@/components/Contextmenu/types'
const contextmenusThumbnails = (): ContextmenuItem[] => {
return [
{
text: '粘贴',
subText: 'Ctrl + V',
handler: pasteSlide,
},
{
text: '全选',
subText: 'Ctrl + A',
handler: selectAllSlide,
},
{
text: '新建页面',
subText: 'Enter',
handler: createSlide,
},
{
text: '开始演示',
subText: 'Ctrl + F',
handler: enterScreening,
},
]
}