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



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


  • 上移一层


  • 下移一层





  • 上移一层


  • 下移一层


3、在data()中定义需要的变量属性
data() {

return {



visible: false,



top: 0,



left: 0

}
}


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)

}

}
},

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

}


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;

}

}
}

.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元素使用,反而没有效果。