<template>
  <div>
    <el-tree :data="treeData" @node-contextmenu="handleContextMenu"></el-tree>
  </div>
</template>
<script>
export default {
  data() {
    return {
      treeData: [
        {
          label: "Gateway",
          id: 1,
          editing: true,
          children: [
            {
              label: "数据采集",
              id: 11,
              children: [
                {
                  label: "I/O点",
                  id: 111,
                },
                {
                  label: "用户点",
                  id: 112,
                },
                {
                  label: "计算点",
                  id: 113,
                },
                {
                  label: "系统点",
                  id: 114,
                },
              ],
            },
            {
              label: "数据服务",
              id: 12,
              children: [
                {
                  label: "Modbus",
                  id: 121,
                },
              ],
            },
            {
              label: "IOT",
              id: 13,
              children: [
                {
                  label: "Mqtt Client",
                  id: 131,
                },
                {
                  label: "Alink",
                  id: 132,
                },
                {
                  label: "Tlink",
                  id: 133,
                },
                {
                  label: "loTDDC",
                  id: 134,
                },
                {
                  label: "Ulink",
                  id: 135,
                },
              ],
            },
          ],
        },
      ],
    };
  },
  methods: {
    handleContextMenu(node, e) {
      // 右击节点时的事件处理
      e.preventDefault();
      this.$contextMenu.show({
        items: [
          {
            label: '新增',
            command: 'add',
          },
          {
            label: '取消',
            command: 'cancel',
          },
        ],
        event: e,
        node: node,
        onclick: this.handleContextMenuItemClick,
      });
    },
    handleContextMenuItemClick({ command }, node) {
      if (command === 'add') {
        // 执行新增操作
        this.addNode(node);
      }
    },
    addNode(parentNode) {
      // 在树节点上添加一个子节点
      const newNode = {
        label: '新节点',
        children: [],
      };
      this.$refs.tree.append(parentNode, newNode);
    },
  },
};
</script>
