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

前往低代码交流专区

更多推荐