Vue3右键菜单组件

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值