页面代码
< div v-for = " data in this.content" :key = " data.id" @contextmenu.prevent = " openMenu($event,data)" >
< ul v-show = " data.visible" :style = " {left:left+' px' ,top:top+' px' }" class = " contextmenu" >
< li @click = " " > 重命名</ li>
< li > 删除</ li>
< li > 编辑</ li>
</ ul>
</ div>
在data()中定义需要的变量属性
data(){
return{
top: 0,
left: 0,
visible: false,
item:null,
}
},
右键打开关闭方法
openMenu(e,data) {
const that=this;
var x = e.pageX;
var y = e.pageY;
that.top = y;
that.left = x;
//将循环之中的每一项添加visible属性,并设置为false
that.content.forEach(function (data) {
that.$set(data, "visible", false);
});
//将循环中的当前点击项的visible设置为true
that.item=data;
that.$set(data, "visible", true);
},
//关闭菜单
closeMenu() {
const that=this;
that.visible=false;
//将循环中的当前点击项的visible设置为false
that.$set(that.item, "visible", false);
},
右键打开关闭的监听方法
watch: {
visible(value) {
if (value) {
document.body.addEventListener('click', this.closeMenu)
} else {
document.body.removeEventListener('click', this.closeMenu)
}
}
},
右键样式
.contextmenu {
margin: 0;
background: #fff;
z-index: 3;
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;
}