页面视图

<ul id="modelTree" class="ztree"></ul>

项目安装JQuery

配置zTree插件的setting,是整个zTree的核心配置,实现拖拽功能,需要配置edit,其中enable一定要设为true,其他参数看需求配置。callback中也配置相关的回调函数。

官方文档,有详细的API

      setting: {
        data: {
          key: {
            name: "deptName"
          },
          simpleData: {
            enable: true,
          },
          keep: { // leaf: true, 表示叶子节点不能变成根节点。parent: true 表示 根节点不能变成叶子节点
            leaf: true,
            parent: true
          },
        },
        // check: {
        //   enable: true
        // },
        callback: {
          // beforeClick: this.beforeClick,
          onClick: this.onClick,
          onRightClick: this.OnRightClick,
          beforeDrag: this.zTreeBeforeDrag,
          beforeDragOpen: this.zTreeBeforeDragOpen,
          beforeDrop: this.zTreeBeforeDrop
        },
        // 开启拖拽
        edit: {
          drag: {
            // 打开移动功能,鼠标左键点击后拖拽
            isMove: true,
            // prev:true,
            // next:true,
            // inner:true
          },
          enable:true, // 实现拖拽,必须设置为true
          showRenameBtn: false,
          showRemoveBtn: false
        }
      },

拖拽函数

    /**移动节点前处理*/
    zTreeBeforeDrag(treeId, treeNodes) {
      // console.log(treeId,treeNodes)
    },
    // 如果返回 false,zTree 将无法进行自动展开操作
    zTreeBeforeDragOpen(treeId, treeNode) {
      // console.log(treeId)
      // console.log(treeNode)
    },
    // 拖拽结束之前
    zTreeBeforeDrop(treeId,treeNodes,targetNode,moveType) {
      var id = treeNodes[0].parentId
      var targetId = targetNode.parentId
      if (id != targetId) {
        this.$message.warning({
          message:'不同部门不能排序'
        })
        return false;
      }
      // console.log(treeNodes)
      let form = new Object();
      form.deptName = treeNodes[0].deptName
      // form.chargeman = treeNodes[0].deptName
      form.leadingOfficial = treeNodes[0].leadingOfficial
      form.parentId = treeNodes[0].parentId
      form.remark = treeNodes[0].remark
      form.id = treeNodes[0].id
      if (moveType == 'inner') { // 嵌套了
        this.$message.warning({
          message:'不同部门不能排序'
        })
        return false;
      } else if (moveType == 'prev') {
        form.sortNo = parseInt(targetNode.sortNo) - 1
      } else if (moveType == 'next') {
        form.sortNo = parseInt(targetNode.sortNo) + 1
      }
      // console.log(form)
      updateDept(form).then(res => {
        if (res.httpCode == 200) {
          this.$message.success({
            message:'部门排序成功'
          })
        }
      }).catch(err => {
        this.$message.error({
          message:'排序失败,请稍后再试'
        })
      })
    },

初始化zTree插件

    ztreeInit() {
      $.fn.zTree.init($("#treeDemo"), this.setting, this.treeList);
      this.sTree = $.fn.zTree.getZTreeObj("treeDemo");
    },