实例-Vue中使用右键菜单之@xunlei/vue-context-menu组件的使用
npm地址——https://www.npmjs.com/package/@xunlei/vue-context-menu
效果
1、安包
npm install @xunlei/vue-context-menu
2、代码
index.vue
<template>
<div id="dataPage">
<el-tree :data="treeData" id="el-tree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
<VueContextMenu class="right-menu" :target="contextMenuTarget" :show="contextMenuVisible"
@update:show="(show) => contextMenuVisible = show">
<a href="javascript:;" @click="createDatabaseOrTable">新建{{ this.menuLabel }}</a>
<a href="javascript:;" @click="deleteDatabaseOrTable">删除{{ this.menuLabel }}</a>
<a href="javascript:;" @click="attribute">属性</a>
<a href="javascript:;" @click="exportDatabaseOrTable">导出{{ this.menuLabel }}</a>
</VueContextMenu>
</div>
</template>
<script>
// 直接在组件中引入使用
import { component as VueContextMenu } from '@xunlei/vue-context-menu'
export default {
components: { VueContextMenu },
data() {
return {
treeData: [
{
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '三级 1-1-1'
}]
}]
},
],
contextMenuTarget: null,
contextMenuVisible: false,
nodeData: { },
defaultProps: {
children: "children",
label: "label",
},
}
},
mounted() {
this.$nextTick(() => {
// vue-context-menu 需要传入一个触发右键事件的元素,等页面 dom 渲染完毕后才可获取
this.contextMenuTarget = document.querySelector('#el-tree')
// 获取所有的 treeitem,循环监听右键事件
const tree = document.querySelectorAll('#el-tree [role="treeitem"]')
tree.forEach(i => {
i.addEventListener('contextmenu', event => {
// 如果右键了,则模拟点击这个treeitem
event.target.click()
})
})
})
},
computed: {
menuLabel() {
return this.nodeData.children == null ? '表' : '数据库';
}
},
methods: {
handleNodeClick(data) {
// console.log(data)
this.nodeData = data
},
createDatabaseOrTable() {
this.contextMenuVisible = false;
console.log("create " + this.menuLabel);
},
deleteDatabaseOrTable() {
this.contextMenuVisible = false;
console.log("delete " + this.menuLabel);
},
attribute() {
this.contextMenuVisible = false;
console.log("show attribute " + this.menuLabel);
},
exportDatabaseOrTable() {
this.contextMenuVisible = false;
console.log("export " + this.menuLabel);
},
}
}
</script>
<style lang="scss">
html,
body {
height: 100%;
}
#dataPage {
margin: 0 0;
font-family: 'Microsoft Yahei', 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
height: 100%;
}
// 右键会选中文字,为了美观将它禁用
#el-tree {
user-select: none;
}
.right-menu {
font-size: 14px;
position: fixed;
background: #fff;
border: solid 1px rgba(0, 0, 0, .2);
border-radius: 3px;
z-index: 999;
display: none;
}
.right-menu a {
width: 150px;
height: 28px;
line-height: 28px;
text-align: center;
display: block;
color: #1a1a1a;
}
.right-menu a:hover {
background: #eee;
color: #fff;
}
.right-menu {
border: 1px solid #eee;
box-shadow: 0 0.5em 1em 0 rgba(0, 0, 0, .1);
border-radius: 1px;
}
a {
text-decoration: none;
}
.right-menu a {
padding: 2px;
}
.right-menu a:hover {
background: #99A9BF;
}
</style>