<script setup>
import { onMounted, onUnmounted, reactive,ref} from 'vue';
const items = [
{id:1,text:'Option 1',action:()=>{alert("options 1 click")}},
{id:2,text:'Option 2',action:()=>{alert("options 2 click")}},
{id:3,text:'Option 3',action:()=>{alert("options 3 click")}},
{id:4,text:'Option 4',action:()=>{alert("options 4 click")}},
]
const visible = ref(false)
const menuStyle = reactive({
position:'fixed',
top:'0px',
left:'0px'
})
function showMenu(x,y){
menuStyle.left = `${x}px`
menuStyle.top = `${y}px`
visible.value = true
}
function hideMenu(){
visible.value = false
}
onMounted(()=>{
window.addEventListener('click',hideMenu)
window.addEventListener('contextmenu',
(event)=>{
event.preventDefault()
showMenu(event.pageX,event.pageY)
}
)
})
onUnmounted(()=>{
window.removeEventListener('click',hideMenu)
window.removeEventListener('context',(event)=>{
event.preventDefault()
showMenu(event.pageX,event.pageY)
})
})
</script>
<template>
<Teleport to="body">
<div v-if="visible" :style="menuStyle" class="context-menu">
<ul>
<li v-for="item in items" :key="item.id" @click="item.action">
{{ item.text }}
</li>
</ul>
</div>
</Teleport>
</template>
<style scoped>
.context-menu{
margin: 0;
padding: 0;
background: white;
border: 1px solid #ccc;
width: 150px;
border-radius: 20px;
}
.context-menu ul{
padding-left: 10px;
}
.context-menu li {
border-radius: 5px;
width: 100%;
list-style: none;
margin: 0;
padding: 8px 0;
cursor: pointer;
color: black;
}
.context-menu li:hover{
background-color: greenyellow;
}
</style>
Vue3右键菜单组件
最新推荐文章于 2024-08-10 17:50:25 发布