当前位置: 首页 > news >正文

vue3 div 点击右键旁边出现弹窗 可做编辑删除 新增操作

 完整代码:

<template>
  <div
      v-for="(item, index) in list"
      :key="index"
      class="list-item"
      @contextmenu.prevent="(e) => showMenu(e, item)"
  >
    {{ item.name }}
  </div>

  <!-- 弹窗组件 -->
  <Teleport to="body">
    <div
        v-if="showContextMenu"
        class="context-menu"
        :style="menuStyle"
    >
      <div class="menu-item" @click="handleAction('edit', currentItem)">
        编辑 {{ currentItem?.name }}
      </div>
      <div class="menu-item" @click="handleAction('delete', currentItem)">
        删除
      </div>
    </div>
  </Teleport>
</template>

<script setup>
import {ref} from 'vue'

const list = ref([
  {id: 1, name: 1},
  {id: 2, name: 2},
  {id: 3, name: 3},
  {id: 4, name: 4},
  {id: 5, name: 5},
  {id: 6, name: 6},
  {id: 7, name: 7},
  {id: 8, name: 8},
])
const showContextMenu = ref(false)
const menuStyle = ref({left: '0px', top: '0px'})
const currentItem = ref(null)

// 右键菜单显示逻辑
const showMenu = (event, item) => {
  currentItem.value = item
  showContextMenu.value = true

  // 位置计算(带视口边界检测)
  const {clientX, clientY} = event
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight

  menuStyle.value = {
    left: `${Math.min(clientX, viewportWidth - 200)}px`,
    top: `${Math.min(clientY, viewportHeight - 150)}px`
  }
}

// 菜单操作处理
const handleAction = (type, item) => {
  console.log('操作类型:', type, '当前数据:', item)
  showContextMenu.value = false
}

// 点击外部关闭(通过事件委托优化)
document.addEventListener('click', () => {
  showContextMenu.value = false
})
</script>

<style>
.list-item {
  padding: 12px;
  border: 1px solid #eee;
  margin: 8px;
  cursor: context-menu;
}

.context-menu {
  position: fixed;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  z-index: 9999;
}

.menu-item {
  padding: 8px 16px;
  transition: background 0.2s;
}

.menu-item:hover {
  background: #f5f5f5;
}
</style>

效果:

http://www.dtcms.com/a/132537.html

相关文章:

  • 案例-索引对于并发Insert性能优化测试
  • 初阶数据结构--二叉树OJ训练
  • 渗透测试学习-概述
  • 搭载DeepSeek|暴雨AI教育一体机加速AI教育普及
  • # linux 设置宽容模式
  • onlyoffice 在线编辑集成
  • 【数据结构_8】栈和队列
  • Java基础——面试自我总结
  • Linux基础IO(七)之理解文件系统
  • 文心一言开发指南03——千帆大模型平台产品优势
  • 力扣每日打卡 3396. 使数组元素互不相同所需的最少操作次数(简单)
  • 【NLP】 22. NLP 现代教程:Transformer的训练与应用全景解读
  • 高速电路中的电阻、电容的选型及应用
  • SCP-Firmware安全通告:CVE-2024-11863和CVE-2024-11864
  • 数组中的第K个最大元素
  • 运行便携软件提示系统从服务器返回一个参照问题解决
  • CVE重要漏洞复现-Fastjson1.2.24-RCE漏洞
  • 一键部署ai画图环境foooocus colab
  • c++------模板进阶
  • 计算机组成原理 第 1 章 概 论
  • C++基础系列【36】异常处理
  • 系统设计模块之安全架构设计(身份认证与授权(OAuth2.0、JWT、RBAC/ABAC))
  • 使用WindSurf生成贪吃蛇小游戏:从零开始的开发之旅
  • websoket 学习笔记
  • 【LLM】A2A 与 MCP:剖析 AI Agent 互联时代的两种关键协议
  • 路由引入配置
  • JMeter的高并发和高频率和分布式
  • matplotlib练习
  • Spring Boot 使用 SMB 协议
  • Sentinel源码—1.使用演示和简介二