话不多说 直接上代码
<template>
<div>
<div @contextmenu="showContextMenu" class="right-clickable">
禁用系统鼠标事件,自定义鼠标右键菜单
<div v-if="contextMenuVisible" class="context-menu">
<!-- 右键菜单的内容 -->
<ul>
<li @click="menuItemClicked('1')">选项1</li>
<li @click="menuItemClicked('2')">选项2</li>
<li @click="menuItemClicked('3')">选项3</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
contextMenuVisible: false,
contextMenuPosition: { x: 0, y: 0 }
}
},
mounted() {
// 监听点击页面其他部分,以隐藏右键菜单
window.addEventListener('click', this.hideContextMenu);
},
beforeDestroy() {
// 移除监听器,以防止内存泄漏
window.removeEventListener('click', this.hideContextMenu);
},
methods: {
showContextMenu(event) {
// 阻止默认右键菜单
event.preventDefault();
// 获取右键点击的位置
this.contextMenuPosition.x = event.clientX;
this.contextMenuPosition.y = event.clientY;
// 显示右键菜单
this.contextMenuVisible = true;
},
hideContextMenu() {
// 隐藏右键菜单
this.contextMenuVisible = false;
},
menuItemClicked(option) {
// 处理菜单选项点击事件
console.log('Clicked:', option);
this.hideContextMenu();
}
}
}
</script>
<style scoped lang="scss">
.right-clickable {
position: relative;
}
.context-menu {
position: absolute;
background-color: #fff;
border: 1px solid #ccc;
padding: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.context-menu ul {
list-style: none;
padding: 0;
margin: 0;
}
.context-menu li {
padding: 5px 10px;
cursor: pointer;
}
</style>