树拖拽功能vue2

<template>
  <div>
    <a-tree draggable :tree-data="gData" @drop="onDrop" />
  </div>
</template>

<script>
const tData = [
  {
    title: '1',
    key: '1',
    children: [
      {
        title: '11',
        key: '11',
        children: [
          { title: '111', key: '111' },
          { title: '222', key: '222' },
          { title: '333', key: '333' },
        ],
      },
      {
        title: '22',
        key: '22',
        children: [{ title: '2333', key: '2333' }],
      },
      {
        title: '33',
        key: '33',
      },
    ],
  },
  {
    title: '2',
    key: '2',
  },
];
import { PAGE_NAMES } from '@/constants/page';

export default {
  name: PAGE_NAMES.TREE_SEARCH,
  data() {
    return {
      gData: tData,
    };
  },
  methods: {
    loop(data, key, callback) {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return this.loop(item.children, key, callback);
        }
      });
    },
    onDrop(info) {
      console.log(this.gData, '拖动前');
      // 目标节点
      const dropKey = info.node.eventKey;
      // 拖动节点
      const dragKey = info.dragNode.eventKey;
      const dropPos = info.node.pos.split('-');
      // -1 上
      // 0 内
      // 1 下
      // 拖动的位置
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

      const data = [...this.gData];

      // 拖动节点的对象
      let dragObj = {};

      if (!info.dropToGap) {
        return false;
      } else if ((info.node.children || []).length > 0 && info.node.expanded && dropPosition === 1) {
        return false;
      } else {
        let a = [];
        let ii = 0;
        this.loop(data, dragKey, (item, index, arr) => {
          a = arr;
          ii = index;
          dragObj = item;
        });
        // 只允许当前节点下的子节点拖动排序
        if (a.some(item => item.key === dropKey)) {
          a.splice(ii, 1);
          let ar = [];
          let i = 0;
          this.loop(data, dropKey, (item, index, arr) => {
            ar = arr;
            i = index;
          });
          if (dropPosition === -1) {
            ar.splice(i, 0, dragObj);
          } else {
            ar.splice(i + 1, 0, dragObj);
          }
        }
      }
      this.gData = data;
      console.log(this.gData, '拖动后');
    },
  },
};
</script>



<style>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值