vue(element-ui)實現(xiàn)右鍵菜單(僅需三步)

一、效果如圖

image.png

二、具體實現(xiàn)

1.首先,在Dom中新建一個div(data中別忘menuVisible,用來控制菜單是否顯示)
<div id="contextmenu"
           v-show="menuVisible"
           class="menu">
        <div class="contextmenu__item"
             @click="ShowView(CurrentRow)">查看</div>
        <div class="contextmenu__item"
             @click="EditData(CurrentRow)">修改</div>
</div>
2.style給上樣式
<style>
.contextmenu__item {
  display: block;
  line-height: 34px;
  text-align: center;
}
.contextmenu__item:not(:last-child) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.menu {
  position: absolute;
  background-color: #fff;
  width: 100px;
  /*height: 106px;*/
  font-size: 12px;
  color: #444040;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 3px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  white-space: nowrap;
  z-index: 1000;
}
.contextmenu__item:hover {
  cursor: pointer;
  background: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}
</style>
3.el-table中給上右鍵點擊事件:@row-contextmenu="rightClick",methods中添加方法
methods: {
    rightClick(row, column, event) {
      this.testModeCode = row.testModeCode
      this.menuVisible = false // 先把模態(tài)框關死,目的是 第二次或者第n次右鍵鼠標的時候 它默認的是true
      this.menuVisible = true // 顯示模態(tài)窗口,跳出自定義菜單欄
      event.preventDefault() //關閉瀏覽器右鍵默認事件
      this.CurrentRow = row
      var menu = document.querySelector('.menu')
      this.styleMenu(menu)
    },
    foo() {
      // 取消鼠標監(jiān)聽事件 菜單欄
      this.menuVisible = false
      document.removeEventListener('click', this.foo) // 關掉監(jiān)聽,
    },
    styleMenu(menu) {
      if (event.clientX > 1800) {
        menu.style.left = event.clientX - 100 + 'px'
      } else {
        menu.style.left = event.clientX + 1 + 'px'
      }
      document.addEventListener('click', this.foo) // 給整個document新增監(jiān)聽鼠標事件,點擊任何位置執(zhí)行foo方法
      if (event.clientY > 700) {
        menu.style.top = event.clientY - 30 + 'px'
      } else {
        menu.style.top = event.clientY - 10 + 'px'
      }
    },
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容