以下示例可直接使用参考:
<template>
<div class="box" @contextmenu.prevent="showContextMenu">
<button @contextmenu.prevent="showContextMenu">点击右键显示右键菜单</button>
<div class="context-menu">
<div class="item" v-for="(item, index) in rightList" :key="index" @click="clickItem(item, index)">
菜单内容{{ index }}--{{item.text}}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'RightMenuCom',
data() {
return {
rightList: [
{ text: '编辑' },
{ text: '复制' },
{ text: '删除' },
{ text: '关闭' },
]
};
},
methods: {
showContextMenu(event) {
event.preventDefault()
const menu = document.querySelector('.context-menu');
menu.style.display = 'block';
const menuHeight = menu.offsetHeight;
const menuWidth = menu.offsetWidth;
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
let top = event.clientY;
let left = event.clientX;
if (top + menuHeight > windowHeight) {
top = windowHeight - menuHeight;
}
if (left + menuWidth > windowWidth) {
left = windowWidth - menuWidth;
}
menu.style.top = top + 'px';
menu.style.left = left + 'px';
document.addEventListener('click', this.hideContextMenu);
},
hideContextMenu() {
const menu = document.querySelector('.context-menu');
menu.style.display = 'none';
document.removeEventListener('click', this.hideContextMenu);
},
clickItem(item, index) {
console.log('点击右键菜单内容', item, index);
}
},
};
</script>
<style lang="less" scoped>
.box {
height: 100%;
}
.context-menu {
position: fixed;
display: none;
/* 其他样式属性 */
width: 150px;
max-height: 150px;
border: 1px solid red;
background: aquamarine;
padding: 10px;
.item {
height: 26px;
line-height: 26px;
cursor: pointer;
}
}
</style>