vue重置鼠标右键,自定义菜单

394 阅读1分钟

原文链接:blog.csdn.net/weixin_4181…

首先写一下右键禁用的代码:

created() {
    this.$nextTick(() => {
        // 禁用右键
        document.oncontextmenu = new Function("event.returnValue=false");
        // 禁止选择网页中的文字,注意此事件不支持对input和textarea无效。
        document.onselectstart = new Function("event.returnValue=false");
    });
},

正题:自定义菜单

1.安装

npm install @xunlei/vue-context-menu

2.注册组件

方式1 利用插件方式全局注册

import VueContextMenu from '@xunlei/vue-context-menu'
import Vue from 'vue'
 
Vue.use(VueContextMenu)

方式2 局部注册

import { component as VueContextMenu } from '@xunlei/vue-context-menu'
 
export default {
    data() {
        return {
            contextMenuTarget: document.body, //绑定的dom
            contextMenuVisible: false, // 菜单
        }
    }
    components: {
        VueContextMenu
    }
}

Props

参数说明类型可选值默认值
target触发右键事件的元素Element--
show是否显示右键菜单Boolean-false

Events

事件名说明事件参数
update:show右键菜单显示/隐藏时触发是否显示

3.代码部分

<VueContextMenu class="right-menu" :target="contextMenuTarget" :show="contextMenuVisible" @update:show="(show) => (contextMenuVisible = show)">
    <a href="javascript:;" @click="copyMsg">复制</a>
    <a href="javascript:;" @click="quoteMsg">引用</a>
    <a href="javascript:;" @click="deleteMsg">删除</a>
</VueContextMenu>
// js
methods:{
    copyMsg() {
        alert("copy");
        this.contextMenuVisible = false;
    },
    quoteMsg() {
        alert("quote");
        this.contextMenuVisible = false;
    },
    deleteMsg() {
        alert("delete");
        this.contextMenuVisible = false;
    },
}
// css
.right-menu {
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.1);
    // display: block;
    // font-family: Microsoft Yahei, Avenir, Helvetica, Arial, sans-serif;
    // -webkit-font-smoothing: antialiased;
    // -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    position: fixed;
    background: #fff;
    // z-index: 999;
    // display: none;
    a {
        padding: 0px 25px;
        // width: 120px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        display: block;
        color: #1a1a1a;
    }
    user agent stylesheet a:-webkit-any-link {
        color: -webkit-link;
        cursor: pointer;
        // text-decoration: underline;
    }
    a:hover {
        background: #409eff;
        color: #fff;
    }
}

效果图如下:

image.png