实现效果
在虚线框内点击任何位置都可以弹出右键菜单,右键菜单的内容是可以自定义的,此处举例:复制、粘贴
引入第三方组件
引入第三方组件vue-context-menu
npm install vue-context-menu
父组件
<template>
<div class="dashboard-container">
<!-- 自定义右键菜单 -->
<div class="contextmenu-wrapper">
<div
class="contextmenu-content"
@contextmenu.prevent.stop="handleContextmenu"
>
右键点击区域
</div>
<contextmenu ref="contextmenu" :menu-type="menuType" />
</div>
</div>
</template>
<script>
import Contextmenu from '@/components/Contextmenu'
export default {
name: 'Dashboard',
components: { Contextmenu },
data() {
return {
menuType: [
{
text: '复制',
disabled: false
},
{
text: '粘贴',
disabled: true
}
]
}
},
methods: {
handleContextmenu() {
this.$refs.contextmenu.$children[0].open()
}
}
}
</script>
<style lang="scss" scoped>
.dashboard-container {
.contextmenu-wrapper {
.contextmenu-content {
text-align: center;
margin: 20px auto;
width: 800px;
height: 200px;
line-height: 200px;
border: 1px dashed #000;
background-color: #fff;
}
}
}
</style>
子组件
<template>
<VueContextmenu ref="contextmenu" class="context-menu">
<li
v-for="(item, index) in menuType"
:key="index"
:class="[item.disabled ? 'context-menu-disabled' : '']"
@click.prevent.stop="handlClick(item)"
@contextmenu.prevent.stop
>
{{ item.text }}
</li>
</VueContextmenu>
</template>
<script>
import VueContextmenu from 'vue-context-menu'
/**
* 组件:<contextmenu ref="contextmenu" :menu-type="menuType" />
*
* 右键事件触发函数内调用:this.$refs.contextmenu.$children[0].open();
*/
export default {
name: 'Contextmenu',
components: {
VueContextmenu
},
props: {
menuType: {
type: Array,
default() {
return [
{
text: '复制',
disabled: false
},
{
text: '粘贴',
disabled: true
}
]
}
}
},
mounted() {
document.addEventListener('click', this.handlHide)
console.log(this.$refs.contextmenu)
},
beforeDestroy() {
document.removeEventListener('click', this.handlHide)
},
methods: {
handlClick(item) {
if (item.disabled) {
this.$refs.contextmenu.ctxVisible = true
} else {
this.$refs.contextmenu.ctxVisible = false
}
},
handlHide() {
this.$refs.contextmenu.ctxVisible = false
}
}
}
</script>
<style lang="scss">
.context-menu {
border: 1px solid #e4e7ed;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.06);
font-size: 14px;
.ctx-menu {
box-sizing: border-box;
position: static;
border: none;
box-shadow: none;
color: #606266;
min-width: 0;
margin: 0;
border-radius: 0;
li {
padding: 5px 20px;
text-align: left;
cursor: pointer;
&.context-menu-disabled {
color: #c0c4cc;
&:hover {
cursor: no-drop;
background-color: #ffffff;
color: #c0c4cc;
}
}
&:hover {
background-color: #409eff;
color: #fff;
}
}
}
}
</style>