vue右键菜单

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue右键菜单

橡皮擦不掉的   2022-05-28 我要评论

封装一个简单的右键菜单,要求右键处出现菜单,点击除了菜单部分可以关闭菜单。

组件

<template>
  <div class="ContextMenu" @click="close" v-show="show">
    <ul class="menuMain" ref="menuMain" :style="{ top: y, left: x }">
      <slot></slot>
    </ul>
  </div>
</template>

<script>
export default {
  name: "ContextMenu",
  mounted() {
    document.addEventListener("contextmenu", this.contextClick);
  },
  data() {
    return {
      x: "0px",
      y: "0px",
      show: false
    };
  },
  methods: {
    //右键事件
    contextClick(e) {
      //阻止默认事件
      e.preventDefault();
      this.show = true;
      this.x = e.clientX + "px";
      this.y = e.clientY + "px";
    },
    close(e) {
      //判断点击区域是否是menuMain的子元素 如果不是则关闭菜单
      if (!this.$refs.menuMain.contains(e.target)) {
        this.show = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.ContextMenu {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  .menuMain {
    position: fixed;
    z-index: 100000;
    list-style: none;
    border-radius: 10px;
    padding: 0;
    margin: 0;
    background-color: #f5f5f5;
    overflow: hidden;
    li{
      padding: 20px;
      cursor: pointer;
      &:hover{
        background-color: #bdbdbd;
      }
    }
  }
}
</style>

使用

<context-menu>
    <li>hello</li>
    <li>hello</li>
</context-menu>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们