互联网技术 · 2024年2月23日

Vue和element-ui实现自定义右键菜单的示例方法

这篇文章主要给大家介绍了关于Vue+element-ui添加自定义右键菜单的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、在所编辑的页面,需要添加右键菜单的元素,绑定contextmenu事件

<template>
<el-button size=”medium” @contextmenu.prevent.native=”openMenu($event)”>
……
</template>

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

<ul v-show=”visible” :style=”{left:left+px,top:top+px}” class=”contextmenu”>
<li>上移一层</li>
<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(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中写右键菜单的样式

.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修饰符对vue组件元素监听原生事件有效,对原生的html元素使用,反而没有效果。

到此这篇关于Vue+element-ui添加自定义右键菜单的文章就介绍到这了,更多相关Vue+element-ui添加自定义右键菜单内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:脚本之家

链接:https://www.jb51.net/article/201648.htm

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册