Vue 1分钟实现右键菜单,懒人的福音!
source link: https://segmentfault.com/a/1190000040858787
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Vue 1分钟实现右键菜单,懒人的福音!
高效实现需求,避免重复造轮子。今天给大家分享的是,如何在最短的时候内实现右键菜单。方法也很简单,一个插件就可以搞定,话不多说,上效果图:
npm install vue-contextmenujs
yarn add vue-contextmenujs
import Contextmenu from "vue-contextmenujs" Vue.use(Contextmenu);
以element-ui
图标为例实现右键菜单,图标会为被渲染为<i class="icon"></i>
,代码如下:
<template> <div style="width:100vw;height:100vh" @contextmenu.prevent="onContextmenu"></div> </template> <script> import Vue from 'vue' import Contextmenu from "vue-contextmenujs" Vue.use(Contextmenu); 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: "custom-class", // 自定义菜单 class zIndex: 3, // 菜单样式 z-index minWidth: 230 // 主菜单最小宽度 }); return false; } } }; </script>
菜单选项都在items
数组里面,可根据需要自行配置。这时候点击右键,菜单弹窗就神奇地出现了,是不是很简单!
自定义样式
打开控制台,查看元素即可查看到菜单的各个 class 名称。最外层的 class 为上面的customClass
属性设置的值,样式可根据需求自行调整。
<style> .custom-class .menu_item__available:hover, .custom-class .menu_item_expand { background: #ffecf2 !important; color: #ff4050 !important; } </style>
以上就基本使用方法,是不是比自己封装节省了大把时间。注意菜单会在点击左键或者滚轮滚动时自动销毁,同时也可调用this.$contextmenu.destroy()
在其他场景自行销毁 。以下是插件的参数配置:
MenuOptions 菜单属性
属性描述类型可选值默认值items菜单结构信息MenuItemOptions[]
——event鼠标事件信息Event
——x菜单显示X坐标, 存在event
则失效number
—0
y菜单显示Y坐标, 存在event
则失效number
—0
zIndex菜单样式z-index
number
—2
customClass自定义菜单classstring
——minWidth主菜单最小宽度number
—150
MenuItemOptions 选项属性
属性描述类型可选值默认值label菜单项名称string
——icon菜单项图标, 生成<i class="icon"></i>
元素string
——disabled是否禁用菜单项boolean
—false
divided是否显示分割线boolean
—false
customClass自定义子菜单classstring
——minWidth子菜单最小宽度number
—150
onClick菜单项点击事件Function()
——children子菜单结构信息MenuItemOptions[]
——分享到此结束,如果对你有所帮助,不要忘了点个赞哦~
听说点赞的人今年人品爆发,年终奖翻倍🤩
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK