在 Vue 3 中实现右键菜单功能,可以通过以下步骤实现:
xml
vue
<template>
<div
@contextmenu.prevent="showContextMenu"
@click="closeContextMenu"
class="container"
>
<!-- 你的页面内容 -->
<div v-if="showMenu"
:style="menuStyle"
class="context-menu">
<div
v-for="(item, index) in menuItems"
:key="index"
class="menu-item"
@click.stop="handleMenuItem(item)"
>
{{ item.label }}
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showMenu = ref(false)
const menuStyle = ref({})
const menuItems = ref([
{ label: '复制', action: 'copy' },
{ label: '粘贴', action: 'paste' },
{ label: '剪切', action: 'cut' }
])
// 显示右键菜单
const showContextMenu = (event) => {
event.preventDefault()
showMenu.value = true
menuStyle.value = {
left: `${event.clientX}px`,
top: `${event.clientY}px`
}
}
// 关闭菜单
const closeContextMenu = () => {
showMenu.value = false
}
// 处理菜单项点击
const handleMenuItem = (item) => {
console.log('执行操作:', item.action)
closeContextMenu()
}
</script>
<style scoped>
.container {
position: relative;
min-height: 100vh;
}
.context-menu {
position: fixed;
background: white;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
z-index: 1000;
}
.menu-item {
padding: 8px 16px;
cursor: pointer;
transition: background 0.2s;
}
.menu-item:hover {
background: #f0f0f0;
}
</style>
实现要点说明:
- 事件监听:
- 使用
@contextmenu.prevent
监听右键事件并阻止默认菜单 - 通过
@click
事件关闭菜单(点击容器任意位置)
- 菜单定位:
- 使用
event.clientX/Y
获取点击坐标 - 通过动态样式绑定定位菜单
- 菜单控制:
- 使用
showMenu
响应式变量控制显示状态 handleMenuItem
处理具体菜单操作
- 样式优化:
- 固定定位保证菜单跟随鼠标
- 添加阴影和圆角提升视觉效果
- 悬停效果增强交互体验
扩展建议:
- 动态菜单项:可以通过 props 接收外部传入的菜单配置
- 图标支持:添加图标字段并集成图标组件
- 动画效果:添加过渡动画提升体验
- 主题支持:通过 CSS 变量实现主题切换
- 禁用状态:添加 disabled 属性控制菜单项可用性
如果需要更复杂的交互,可以考虑使用第三方库如 vue-context-menu
,但上述实现已能满足大多数基础需求。