Vue + element控制鼠标右键菜单

1、在页面元素绑定contextmenu事件

元素中使用@contextmenu.prevent.native="openMenu($event)"绑定事件

<template>
  <span size="medium" @contextmenu.prevent.native="openMenu($event)" />
</template>

2、在页面编写右键菜单内容

<ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
      <li>历史记录</li>
 </ul>

3、在data()中定义需要的变量属性

data() { 
    return {
            visible: false,
            top: 0,
            left: 0
    }
}

4、监控visible的变化,来触发关闭右键菜单,调用关闭菜单的方法

watch: {
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },

5、在method中定义openMenu、closeMenu的两个方法

openMenu(e) {
      const menuMinWidth = 105
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = e.clientY - 60 // fix 位置bug
      this.visible = true
    },
    closeMenu() {
      this.visible = false
    }

猜你喜欢

转载自www.cnblogs.com/gaofz/p/11995001.html