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>
相关推荐
维克兜率天13 小时前
【维克】KDJ量化实战:如何用它判断买卖点?
前端
维克兜率天16 小时前
【维克】RSI相对强弱指数:判断多空力量的温度计
前端
FRing031 天前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
YIAN1 天前
我踩完 DeepAgents 记忆模块的坑,才搞懂长期记忆和摘要不是一回事
前端·javascript·agent
YIAN1 天前
用 Deep Agents 复现一个深度调研助手:从主 Agent、子 Agent 到 Skill
javascript·agent
map_3d_vis1 天前
百度地图 JSAPI 4.0 是什么:版本说明与能力概览
前端·javascript·webgl·地图·百度地图
码云之上1 天前
微信小程序设备指纹实践,删了重装还能认出这台手机吗?
前端·安全·微信小程序
JavaGuide1 天前
刚刚,GLM-5.4 正式发布,实测来了:看图用 Blender 建凉亭、做技术视频,再画一辆真能传动的自行车
前端·后端
乌鲁木齐德润恒圣信息科技有限公司1 天前
GEO生成式引擎优化:技术原理与43引擎自动测试系统
大数据·前端·人工智能
泯泷1 天前
第一章:Lit简介 - 现代Web组件标准
前端·javascript·web components