vue项目中添加自定义右键菜单

完整demo组件

<template>
  <div class="test-menu" @contextmenu.prevent="openMenu($event)">
    菜单测试区
  div>

  
  <ul class="custom-contextmenu" ref="customContextMenu">
    <li @click="handleMenuItemClick('edit')">编辑li>
    <li @click="handleMenuItemClick('delete')">删除li>
  ul>
template>

<script setup>
import { ref } from 'vue';
let customContextMenu = ref(null);
const openMenu = (e) => {
  let top = e.pageY;
  let left = e.pageX;
  let ele = customContextMenu.value;
  ele.style.top = top + 'px';
  ele.style.left = left + 'px';
  ele.style.display = 'block';
};

window.addEventListener('click', () => {
  let menuElement = customContextMenu.value;
  menuElement.style.display = 'none';
});

const handleMenuItemClick = (type) => {
  console.log('type:', type);
};
script>

<style scoped lang="scss">
.test-menu {
  width: 200px;
  height: 200px;
  background-color: lightblue;
}

.custom-contextmenu {
  border: 1px solid #ccc;
  width: 80px;
  padding: 0;
  list-style: none;
  border-bottom: none;
  position: fixed;
  display: none;
  background-color: #fff;
  li {
    width: 80px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    border-bottom: 1px solid #ccc;
    cursor: pointer;
    &:hover {
      background-color: skyblue;
    }
  }
}
style>

你可能感兴趣的:(vue,vue.js,javascript,前端)