element-uiel-tree组件添加右键菜单在 github 上有⼀个 项⽬实现了以上功能。具体使⽤在项⽬的 README.md 中写的⼗分清楚了。
我的实现效果如图:
实现代码如下:
<template>
<div>
<div id="dataPage">
<el-tree :data="data" id="el-tree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
<context-menu class="right-menu"
:target="contextMenuTarget"
:show="contextMenuVisible"
@update:show="(show) => contextMenuVisible = show">
<a href="javascript:;" @click="createDatabaseOrTable">新建{{uLabel}}</a>
<a href="javascript:;" @click="deleteDatabaseOrTable">删除{{uLabel}}</a>
<a href="javascript:;" @click="attribute">属性</a>
<a href="javascript:;" @click="exportDatabaseOrTable">导出{{uLabel}}</a>
</context-menu>
</div>
</div>
</template>
<script>
export default {
name:'DatabasesContent',
data() {
return {
contextMenuTarget: null,
contextMenuVisible: false,
nodeData: {},
data: [{
label: '⼀级 1',
children: [{
label: '⼆级 1-1',
label: '⼆级 1-2',
}]
}, {
label: '⼀级 2',
children: [{
label: '⼆级 2-1',
}, {
label: '⼆级 2-2',
}]
}, {
label: '⼀级 3',
label: '⼀级 3',
children: [{
label: '⼆级 3-1',
}, {
label: '⼆级 3-2',
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
handleNodeClick(data) {
// console.log(data)
},
createDatabaseOrTable() {
console.log("create " + uLabel);
},
deleteDatabaseOrTable() {
console.log("delete " + uLabel);
},
attribute() {
console.log("show attribute " + uLabel);
},
exportDatabaseOrTable() {
console.log("export " + uLabel);
}
},
mounted() {
this.$nextTick(() => {
// vue-context-menu 需要传⼊⼀个触发右键事件的元素,等页⾯ dom 渲染完毕后才可获取        tMenuTarget = 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() {
deData.children == null ? '表' : '数据库';
}
},
};
</script>
<style>
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;
nodeselector
}
.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>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。