1.封装一个右键菜单
<template>
<teleport to="body">
<div v-if="contextMenuVisible" class="right-click-menu" :style="{ top: `${top}px`, left: `${left}px` }">
<ul v-for="(item, index) in menuList" :key="index">
<li @click="handleItemClick(item)">{{ item }}</li>
</ul>
</div>
</teleport>
</template>
<script setup lang='ts'>
defineProps(['top', 'left', 'handleItemClick', 'contextMenuVisible', 'menuList'])
</script>
<style scoped lang='scss'>
.right-click-menu {
position: fixed;
background-color: #fff;
box-shadow: 0 15px 30px rgba(0, 0, 0, .3);
z-index: 1000;
border-radius: 10px;
width: 118px;
font-size: 14px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
text-indent: 18px;
display: flex;
justify-content: center;
align-items: center;
}
li {
width: 110px;
height: 40px;
cursor: pointer;
border-radius: 10px;
display: flex;
align-items: center;
}
li:hover {
background-color: #F3F4F6;
}
</style>
2.引入组件使用
<template>
<div v-for="item in friendMessage" :key="item.id">
<div class="mes">
<span class="mesSpan" @contextmenu="showContextMenu($event, item)">{{ item.chatContent }}</span>
</div>
</div>
<div class="rightClick">
<RightClickMenu v-if="contextMenuVisible" :top="contextMenuTop" :left="contextMenuLeft" :handleItemClick="handleContextMenuItemClick" :visible="contextMenuVisible" :menuList="menuList" />
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import RightClickMenu from "@/components/RightClickMenu/index.vue";
let menuList = ref(['复制', '转发', '收藏', '多选', '撤回', '删除']);
const targetElement = ref(null);
const contextMenuVisible = ref(false);
const contextMenuTop = ref(0);
const contextMenuLeft = ref(0);
const showContextMenu = (event, item) => {
event.preventDefault();
contextMenuVisible.value = true;
contextMenuTop.value = event.clientY;
contextMenuLeft.value = event.clientX;
const menuHeight = 240;
const windowHeight = window.innerHeight;
if (event.clientY + menuHeight > windowHeight) {
contextMenuTop.value -= menuHeight;
}
window.addEventListener("click", hideContextMenu);
};
const hideContextMenu = () => {
contextMenuVisible.value = false;
window.removeEventListener("click", hideContextMenu);
};
const handleContextMenuItemClick = (item) => {
console.log(`Clicked on ${item}`);
hideContextMenu();
};
<script>
3.效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/11aabfb47acb4bc0ac0b418bed3dbb61.png)