Vue3 实现右击弹出操作选项

通过自定义指令来实现右击弹出操作选项的功能。

  1. 创建一个自定义指令 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;
  1. 在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');
  1. 在组件中使用这个指令:
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>
相关推荐
Marshmallowc几秒前
从源码深度解析 React:Hook 如何在 Fiber 中存储?DOM Ref 如何绑定?
前端·react.js·前端框架·fiber
Eiceblue1 分钟前
Vue文档编辑器(Word默认功能)示例
前端·vue.js·word
Mr Xu_5 分钟前
在 Vue 3 中集成 WangEditor 富文本编辑器:从基础到实战
前端·javascript·vue.js
No Silver Bullet5 分钟前
HarmonyOS NEXT开发进阶(二十三):多端原生App中通过WebView嵌套Web应用实现机制
前端·华为·harmonyos
光影少年9 分钟前
react和vue中的优点和缺点都有哪些
前端·vue.js·react.js
web_Hsir9 分钟前
uniapp + vue2 + pfdjs + web-view 实现安卓、iOS App PDF预览
android·前端·uni-app
css趣多多11 分钟前
画系统的整体思路
vue.js
EndingCoder11 分钟前
Node.js 与 TypeScript:服务器端开发
前端·javascript·typescript·node.js
打小就很皮...11 分钟前
基于 React 实现 Vditor 的可复用 Markdown 渲染组件
前端·react.js·markdown·vditor
EndingCoder19 分钟前
React 与 TypeScript:组件类型化
前端·javascript·react.js·typescript·前端框架