<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>
树拖拽功能vue2
最新推荐文章于 2024-05-08 16:56:37 发布