先看效果:
实现代码:
<div
v-for="(item, index) in canvasItem.value"
//此事件加在目标方法上,item为动态参数,根据实际情况可传可不传
@contextmenu.prevent="openMenu($event, item)"
:key="index"
>
</div>
methods:
openMenu(e, item) {
this.rightClickItem = item;
//获取右击时得坐标
var x = e.pageX;
var y = e.pageY;
//top,left在data种定义,初始值为0
//top,left是右键菜单得坐标值,可以通过运算调整
this.top = y - 50;
this.left = x - 50;
this.gridCustomizeVisible = true;
},
closeMenu() {
this.gridCustomizeVisible = false;
},
菜单:
<ul
//控制菜单显示
v-show="gridCustomizeVisible"
//坐标值
:style="{ left: left + 'px', top: top + 'px' }"
class="contextmenu"
>
<li @click="editComponent()">编辑</li>
<li @click="gridCustomizeVisible = false">取消</li>
</ul>
data种变量定义:
data() {
return {
top: 0,
left: 0,
gridCustomizeVisible: false
}
}
css样式:
<style lang="less" scoped>
.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;
}
</style>
如果有点击空白处菜单关闭得需求:还可以通过监听gridCustomizeVisible变量达到目的
watch: {
//变量名
gridCustomizeVisible(val) {
if (val) {
//点击事件,调用方法
document.body.addEventListener("click", this.closeMenu);
} else {
document.body.removeEventListener("click", this.closeMenu);
}
},
},
实现功能借助于以下博主得洪荒之力,感谢