Vue+element ui Example Method for Adding Custom Right click Menu
- 2021-10-13 06:07:05
- OfStack
1. In the edited page, you need to add the element of the right-click menu and bind the contextmenu event
<template>
<el-button size="medium" @contextmenu.prevent.native="openMenu($event)">
......
</template>
2. Write the right-click menu content on the page
<ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
<li> Move up 1 Layer </li>
<li> Move down 1 Layer </li>
</ul>
3. Define the required variable attributes in data ()
data() {
return {
visible: false,
top: 0,
left: 0
}
}
4. Observe the change of visible to trigger the closing of the right-click menu and call the method of closing the menu
watch: {
visible(value) {
if (value) {
document.body.addEventListener('click', this.closeMenu)
} else {
document.body.removeEventListener('click', this.closeMenu)
}
}
},
5. Define two methods to open and close the right-click menu in method
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 Position bug
this.visible = true
},
closeMenu() {
this.visible = false
}
6. Write the style of right-click menu in style
.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;
}
}
}
Note: The. native modifier is effective for vue component elements listening for native events, but it has no effect for native html elements.