原生Vue 实现右键菜单组件功能
时间:2020-11-16 11:56:37|栏目:vue|点击: 次
Vue 原生实现右键菜单组件, 零依赖
快速安装
npm install vue-contextmenujs
使用
测试中使用的是 element-ui 图标
import Contextmenu from "vue-contextmenujs" Vue.use(Contextmenu); <template> <div id="app" style="width:100vw;height:100vh" @contextmenu.prevent="onContextmenu"></div> </template> <script> export default { methods: { onContextmenu(event) { this.$contextmenu({ items: [ { label: "返回(B)", onClick: () => { this.message = "返回(B)"; console.log("返回(B)"); } }, { label: "前进(F)", disabled: true }, { label: "重新加载(R)", divided: true, icon: "el-icon-refresh" }, { label: "另存为(A)..." }, { label: "打印(P)...", icon: "el-icon-printer" }, { label: "投射(C)...", divided: true }, { label: "使用网页翻译(T)", divided: true, minWidth: 0, children: [{ label: "翻译成简体中文" }, { label: "翻译成繁体中文" }] }, { label: "截取网页(R)", minWidth: 0, children: [ { label: "截取可视化区域", onClick: () => { this.message = "截取可视化区域"; console.log("截取可视化区域"); } }, { label: "截取全屏" } ] }, { label: "查看网页源代码(V)", icon: "el-icon-view" }, { label: "检查(N)" } ], event, customClass: "class-a", zIndex: 3, minWidth: 230 }); return false; } } }; </script>
ps:下面看下vue点击菜单以外区域,隐藏菜单操作
data() { return { menuShow: false //v-show标识隐藏显示 } }, mounted (){ let _this = this; document.addEventListener('click', function (e) { // 下面这句代码是获取 点击的区域是否包含你的菜单,如果包含,说明点击的是菜单以外,不包含则为菜单以内 let flag = e.target.contains(document.getElementsByClassName('menu-class')[0]) console.log(flag) if(!flag) return _this.menuShow = false }) }
总结