利用element实现简单右键

发布于:2024-05-23 ⋅ 阅读:(30) ⋅ 点赞:(0)

利用element-plus中的el-menu实现简单右键

实现如下

<template>
  <main class="mainClass"  @contextmenu="showMenu($event)"> 
  </main>

  <el-menu
    :default-active="1"
    class="el-menu-demo"
    mode="vertical"
    :collapse="isCollapse"
    v-show="menuShow"
    @close="hideMenu"
    @open="openItem"
    ref="menuRef"
    :style="{ left: left + 'px', top: top + 'px' }"
  >
    <el-menu-item index="1">Processing Center</el-menu-item>
    <el-sub-menu index="2">
      <template #title>Workspace</template>
      <el-menu-item index="2-1">item one</el-menu-item>
      <el-menu-item index="2-2">item two</el-menu-item>
      <el-menu-item index="2-3">item three</el-menu-item>
    </el-sub-menu>
  </el-menu>
  
</template>

<script setup>

import { watch ,ref } from 'vue';

const activeIndex = ref('0')
const menuShow = ref(false)
const isCollapse = ref(true)
const menuRef = ref(null)
const left = ref(0)
const top = ref(0)

function hideMenu()
{
  menuShow.value = false;
}
function openItem(index, indexPath)
{
  console.log(index, indexPath)
}

function showMenu(e)
{
  menuShow.value = true;
  left.value = e.clientX+1;
  top.value = e.clientY+1;
  //阻止默认行为
  e.preventDefault();
}

//监听menuShow的变化,当它为true时,给body绑定一个点击事件,当点击时,隐藏menu
watch(menuShow,(newValue, oldValue) => {
  if(newValue)
  {
    document.body.addEventListener('click', hideMenu)
  } 
  else 
  {
    document.body.removeEventListener('click', hideMenu)
  }
})

</script>


<style scoped>
.mainClass
{
  width: 500px;
  height: 500px;
  background-color: #f0f0f0;
}
.el-menu-demo
{
  position: absolute;
  left: 0;
  top: 0;
  z-index: 100;
  width: 120px;
  /* background-color: rgb(167, 184, 184); */
}
</style>

推荐一个 v-contextmenu (cybernika.net)


网站公告

今日签到

点亮在社区的每一天
去签到