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

Vue实现自定义右键菜单的示例

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

一、写原生方法

vue添加自定义右键菜单的完整实例

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

<li
v-for=”item in resourceList”
:key=”item.id”
@click=”handleClickFolder(item)”
@contextmenu.prevent=”openMenu($event,item)”
>

</li>

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(e, item) {
this.rightClickItem = item;

var x = e.pageX;
var y = e.pageY;

this.top = y;
this.left = x;

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);
}

.contextmenu li {
margin: 0;
padding: 7px 16px;
cursor: pointer;
}

.contextmenu li:hover {
background: #eee;
}

二、使用插件vue-context-menu

demo地址

github地址

安装:

npm install vue-contextmenu –save

引用:

import VueContextMenu from vue-contextmenu
Vue.use(VueContextMenu)

使用:

<template>
<div id=”app” @contextmenu=”showMenu”
style=”width: 100px;height: 100px;margin-top: 20px;background: red;”>
<vue-context-menu :contextMenuData=”contextMenuData”
@savedata=”savedata”
@newdata=”newdata”></vue-context-menu>
</div>
</template>
<script>
export default {
name: app,
data () {
return {
// contextmenu data (菜单数据)
contextMenuData: {
// the contextmenu name(@1.4.1 updated)
menuName: demo,
// The coordinates of the display(菜单显示的位置)
axis: {
x: null,
y: null
},
// Menu options (菜单选项)
menulists: [{
fnHandler: savedata,
icoName: fa fa-home fa-fw,
btnName: Save
}, {
fnHandler: newdata,
icoName: fa fa-home fa-fw,
btnName: New
}]
}
}
},
methods: {
showMenu () {
event.preventDefault()
var x = event.clientX
var y = event.clientY
this.contextMenuData.axis = {
x, y
}
},
savedata () {
alert(1)
},
newdata () {
console.log(newdata!)
}
}
}
</script>

tip:有说不兼容ie的,具体没有测试

到此这篇关于vue添加自定义右键菜单的文章就介绍到这了

来源:脚本之家

链接:https://www.jb51.net/article/201645.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.