vue 如何实现右键菜单

本文介绍了一个用Vue编写的右键菜单组件,展示如何在用户点击按钮时弹出菜单,以及如何处理菜单的显示、位置调整和隐藏,同时涉及CSS样式设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下示例可直接使用参考:

<template>
  <div class="box" @contextmenu.prevent="showContextMenu">
    <button @contextmenu.prevent="showContextMenu">点击右键显示右键菜单</button>
    <div class="context-menu">
      <div class="item" v-for="(item, index) in rightList" :key="index" @click="clickItem(item, index)">
        菜单内容{{ index }}--{{item.text}}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RightMenuCom',
  data() {
    return {
      rightList: [
        { text: '编辑' },
        { text: '复制' },
        { text: '删除' },
        { text: '关闭' },
      ]
    };
  },
  methods: {
    showContextMenu(event) {
      event.preventDefault()
      const menu = document.querySelector('.context-menu');
      menu.style.display = 'block';

      const menuHeight = menu.offsetHeight;
      const menuWidth = menu.offsetWidth;
      const windowHeight = window.innerHeight;
      const windowWidth = window.innerWidth;

      let top = event.clientY;
      let left = event.clientX;

      if (top + menuHeight > windowHeight) {
        top = windowHeight - menuHeight;
      }

      if (left + menuWidth > windowWidth) {
        left = windowWidth - menuWidth;
      }

      menu.style.top = top + 'px';
      menu.style.left = left + 'px';
      document.addEventListener('click', this.hideContextMenu);
    },
    hideContextMenu() {
      const menu = document.querySelector('.context-menu');
      menu.style.display = 'none';
      document.removeEventListener('click', this.hideContextMenu);
    },
    clickItem(item, index) {
      console.log('点击右键菜单内容', item, index);
    }
  },
};
</script>

<style lang="less" scoped>
.box {
  height: 100%;
}
.context-menu {
  position: fixed;
  display: none;
  /* 其他样式属性 */
  width: 150px;
  max-height: 150px;
  border: 1px solid red;
  background: aquamarine;
  padding: 10px;
  .item {
    height: 26px;
    line-height: 26px;
    cursor: pointer;
  }
}
</style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值