需求是tree组件实现新增与删除节点的功能,在查阅了很多文章之后,缝缝补补实现了功能

npm install @xunlei/vue-context-menu --save

<div id="dataPage">
  <el-tree
    id="el-tree"
    :data="flowTree.root"
    :props="flowTree.props"
    @node-click="selectFlow"
    @node-contextmenu="rightClick"/>
  <vue-context-menu
    :target="contextMenuTarget"
    :show="contextMenuVisible"
    class="right-menu"
    @update:show="(show) => contextMenuVisible = show">
    <a
      href="javascript:;"
      @click="createDatabaseOrTable">新建</a>
    <a
      href="javascript:;"
      @click="deleteDatabaseOrTable">删除</a>
  </vue-context-menu>
</div>

import { component as VueContextMenu } from '@xunlei/vue-context-menu';
components: {
  'vue-context-menu': VueContextMenu,
},
data(){
  return {
  	flowTree: {
      root: [],
      props: {
        label: 'name',
        children: 'children',
      },
    },
    treeNodeData: '', // 存当前数据
    treeNode: '', // 存当前节点信息
    contextMenuVisible: false, // 让菜单显示
    contextMenuTarget: null,
  }
},
methods: {
  rightClick(e, data, node) {
      this.treeNodeData = data;// 存当前数据
      this.treeNode = node;// 存当前节点信息
      console.log('rightClick', this.treeNodeData, this.treeNode);
      this.contextMenuVisible = true;// 让菜单显示
      console.log('0', e, '1', e.screenX, '2', e.screenY);
      const ele = document.querySelector('.right-menu');
      ele.style.position = 'fixed';
      ele.style.top = `${e.clientY}px`;
      ele.style.left = `${e.clientX + 10}px`; //根据鼠标点击位置设置菜单出现
  },
  createDatabaseOrTable() {
    this.contextMenuVisible = false;
    console.log('createDatabaseOrTable', this.treeNodeData, this.treeNode);
  },
  deleteDatabaseOrTable() {
    this.contextMenuVisible = false;
    console.log('deleteDatabaseOrTable', this.treeNodeData, this.treeNode);
  },
}

<style lang="less">
	#dataPage {
    margin: 0 0;
    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;
    padding: 2px;
  }
  .right-menu a:hover {
    background: #bbb;
    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;
  }
</style>

一键复制即可使用,也是在大佬们的基础上实现的,应该不会有问题,具体的功能点大家应该都能实现,有问题的话一起讨论

Logo

前往低代码交流专区

更多推荐