vue3实现右键菜单

vue3原生实现右键菜单

效果图
在这里插入图片描述
代码

<template>
  <div class="home">
    <!-- 在需要右键菜单的元素,绑定contextmenu事件 -->
    <div 
    	class="test" v-for="item in menus" :key="item" 
    	@contextmenu.prevent="openMenu($event,item)">{{item}}</div>
    	
    <!-- 右键菜单部分 -->
  <ul v-show="visible1"
    :style="{ left: position.left + 'px', top: position.top + 'px', display: (visible1 ? 'block' : 'none') }"
    class="contextmenu">
    <div class="item">
      复制Vue代码
    </div>
    <div class="item" @click="copySvg(rightClickItem.resource, rightClickItem.name)">
      复制SVG
    </div>
    <div class="item" @click="downSvg(rightClickItem.resource, rightClickItem.name)">
      下载SVG
    </div>
    <div class="item" @click="downPng(rightClickItem.resource, rightClickItem.name)">
      下载PNG
    </div>
</ul>
  </div>
</template>
<script  lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
const visible1 = ref(false)
const position = ref({
  top: 0,
  left: 0
})
const rightClickItem = ref('')
const openMenu = (e:MouseEvent, item:any) => {
  visible1.value = true
  position.value.top = e.pageY
  position.value.left = e.pageX
  rightClickItem.value = item
}
const closeMenu = () => {
  visible1.value = false
}
watch(visible1, () => {
  if (visible1.value) {
    document.body.addEventListener('click', closeMenu)
  } else {
    document.body.removeEventListener('click', closeMenu)
  }
})
</script>
<style scoped lang="scss">
.contextmenu {
  width: 100px;
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  .item {
    padding: 0 15px;
    height: 35px;
    width: 100%;
    line-height: 35px;
    color: rgb(29, 33, 41);
    cursor: pointer;

  }
  .item:hover {
    background: rgb(229, 230, 235);
  }
}
</style>
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值