最近项目中遇到一个tree型数据的的操作的功能,代码简单如下:
<a-tree
showLine
showIcon
:draggable="draggable"
:expandedKeys="expandedKeys"
:treeData="treeData"
@drop="onDrag"
@expand="onExpand"
>
<template v-if="nodeBtns" slot="custom" slot-scope="item">
<a-button size="small" icon="plus" @click="toAdd(item)" />
<a-button size="small" icon="edit" @click="toEdit(item)" />
<a-button size="small" icon="delete" @click="deleteTreeNode(item)" />
</template>
<a-spin :spinning="spinning" />
</a-tree>
增加操作代码:
toAdd(item) {
this.item={title:'', parentId:item.key}
this.changeVisible=true // 这是弹窗,弹窗内输入title
},
treeAction (node, id, fn) {
node.some((item,index) => {
if (item.key === id) {
fn(node, item, index)
return true;
}
if (item.children && item.children.length) {
this.treeAction(item.children, id, fn);
}
});
},
handleAdd(){
let that=this
... // api操作
// treeData数据的操作
this.treeAction(this.treeData, this.item.parentId, (node, item, index) => {
item.children = item.children || [];
that.item.key=data // that.item为保存当前节点数据的变量
that.item.scopedSlots = { icon: "custom" }
item.children.push(that.item)
});
...
},
修改和添加类似,点击修改则弹窗修改窗体,然后确定则进行修改:
handleChange(){
... // api操作
// treeData数据操作
this.treeAction(this.treeData, this.item.parentId, (node, item, index) => {
item.children = item.children || [];
that.item.key=data
that.item.scopedSlots = { icon: "custom" }
item.children.push(that.item)
});
删除操作:
delete(item) {
let that = this;
this.$confirm({
title: "确认删除吗??",
content: "点击确定删除",
onOk() {
... // api操作
// treeData操作
that.treeAction(that.treeData, item.key, (node, item, index) => {
node.splice(index, 1);
});
},
onCancel() {},
});
},
拖拽操作:
onDrag(info){
const node = info.node;
const dragNode = info.dragNode;
const dropKey = info.node.dataRef.key;
const dragKey = info.dragNode.dataRef.key;
const dropPos = info.node.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
const loop = (data, key, callback) => {
data.forEach((item, index, arr) => {
if (item.key === key) {
return callback(item, index, arr);
}
if (item.children) {
return loop(item.children, key, callback);
}
});
};
const data = [...this.treeData];
let dragObj;
loop(data, dragKey, (item, index, arr) => {
arr.splice(index, 1);
dragObj = item;
});
if (!info.dropToGap) {
loop(data, dropKey, item => {
item.children = item.children || [];
item.children.push(dragObj);
});
} else {
let ar;
let i;
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);
}
}
... // api
// treeData重新赋值
this.treeData= data
},