以下是一个使用Vue 2和Element UI的el-tree组件实现的简单例子,展示了如何添加右键菜单以便能够添加和删除组织。
<template>
<div>
<el-tree
:data="treeData"
node-key="id"
:props="defaultProps"
@node-contextmenu="openMenu"
@node-click="handleNodeClick"
>
<!-- Custom tree node -->
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button
type="text"
size="mini"
@click="() => append(data)"
>
添加
</el-button>
<el-button
type="text"
size="mini"
@click="() => remove(node, data)"
>
删除
</el-button>
</span>
</span>
</el-tree>
<!-- Context menu -->
<div
v-show="menuVisible"
:style="{ top: menuTop + 'px', left: menuLeft + 'px' }"
class="contextmenu"
>
<el-button @click="add">添加</el-button>
<el-button @click="del">删除</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
menuVisible: false,
menuTop: 0,
menuLeft: 0,
treeData: [
{
id: 1,
label: '组织1',
children: [
{
id: 2,
label: '组织1-1'
}
]
}
],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
openMenu(event, data, node, element) {
this.menuVisible = true;
this.menuTop = event.clientY;
this.menuLeft = event.clientX;
},
handleNodeClick(data) {
console.log(data);
},
append(data) {
const newChild = { id: id++, label: `组织${id}`, children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
},
remove(node, data) {
const parent = node.parent;
const children = parent.data.children || parent.data;
const index = children.findIndex(d => d.id === data.id);
children.splice(index,