通过自定义指令来实现右击弹出操作选项的功能。
- 创建一个自定义指令 v-context-menu.js:
javascript
// v-context-menu.js
import { DirectiveBinding } from 'vue';
const ContextMenu = {
mounted(el: HTMLElement, binding: DirectiveBinding) {
const menu = binding.value; // 获取传入的菜单数据
if (!menu) return;
el.addEventListener('contextmenu', (e) => {
e.preventDefault();
const mouseX = e.clientX;
const mouseY = e.clientY;
// 创建一个菜单元素并添加到body
const menuElement = document.createElement('div');
menuElement.style.position = 'absolute';
menuElement.style.left = `${mouseX}px`;
menuElement.style.top = `${mouseY}px`;
menuElement.style.backgroundColor = 'white';
menuElement.style.zIndex = '1000';
menuElement.style.border = '1px solid #ccc';
// 构建菜单项
menu.forEach((item) => {
const menuItem = document.createElement('div');
menuItem.textContent = item.label;
menuItem.style.padding = '5px';
menuItem.style.cursor = 'pointer';
menuItem.addEventListener('click', item.action);
menuElement.appendChild(menuItem);
});
document.body.appendChild(menuElement);
});
// 清理菜单元素
el.addEventListener('click', () => {
const menuElements = document.querySelectorAll('.context-menu');
menuElements.forEach((menuElement) => {
menuElement.remove();
});
});
},
};
export default ContextMenu;
- 在Vue应用中注册这个自定义指令:
javascript
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import ContextMenuDirective from './directives/v-context-menu';
const app = createApp(App);
app.directive('context-menu', ContextMenuDirective);
app.mount('#app');
- 在组件中使用这个指令:
html
<template>
<div v-context-menu="menuOptions">
<!-- 右击这个区域会弹出菜单 -->
右击我
</div>
</template>
<script setup>
import { ref } from 'vue';
const menuOptions = ref([
{
label: '选项一',
action: () => alert('选项一被点击'),
},
{
label: '选项二',
action: () => alert('选项二被点击'),
},
]);
</script>