1、在所編輯的頁(yè)面,需要添加右鍵菜單的元素,綁定contextmenu事件
1
2
3
4
|
< template > < el-button size = "medium" @ contextmenu.prevent.native = "openMenu($event)" > ...... </ template > |
2、在頁(yè)面編寫(xiě)右鍵菜單內(nèi)容
1
2
3
4
|
< ul v-show = "visible" :style = "{left:left+'px',top:top+'px'}" class = "contextmenu" > < li >上移一層</ li > < li >下移一層</ li > </ ul > |
3、在data()中定義需要的變量屬性
1
2
3
4
5
6
7
|
data() { return { visible: false , top: 0, left: 0 } } |
4、觀察visible的變化,來(lái)觸發(fā)關(guān)閉右鍵菜單,調(diào)用關(guān)閉菜單的方法
1
2
3
4
5
6
7
8
9
|
watch: { visible(value) { if (value) { document.body.addEventListener( 'click' , this .closeMenu) } else { document.body.removeEventListener( 'click' , this .closeMenu) } } }, |
5、在method中定義打開(kāi)右鍵菜單和關(guān)閉右鍵菜單的兩個(gè)方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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 } |
6、在style中寫(xiě)右鍵菜單的樣式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
.contextmenu { margin : 0 ; background : #fff ; z-index : 3000 ; position : absolute ; list-style-type : none ; padding : 5px 0 ; border-radius: 4px ; font-size : 12px ; font-weight : 400 ; color : #333 ; box-shadow: 2px 2px 3px 0 rgba( 0 , 0 , 0 , 0.3 ); li { margin : 0 ; padding : 7px 16px ; cursor : pointer ; &:hover { background : #eee ; } } } |
注意:.native修飾符對(duì)vue組件元素監(jiān)聽(tīng)原生事件有效,對(duì)原生的html元素使用,反而沒(méi)有效果。
到此這篇關(guān)于Vue+element-ui添加自定義右鍵菜單的文章就介紹到這了,更多相關(guān)Vue+element-ui添加自定義右鍵菜單內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_42991509/article/details/100736595