首先先来看一下数据结构
这是典型的树结构,组织树接口返回的结构都是这样的,每个对象下都有个children字段,这个children就是子节点,如果需要实现添加只需要在点击添加时给点击对象的children字段下在push一条数据就行
新增
// 递归算法 创建用户树结构
// 递归遍历树,通过map遍历直接修改原数组数据,数组其他的数据不变
getNewTree(obj) {
obj.map(item => {
if (item.id == this.addId) {
// console.log('打印', item.id, this.addId)
item.children.push({
bzValue: this.form.region,
zbname: this.treeName,
level: item.level + 1,
// id: this.form.name,
zbid: this.form.name,
zbrange: { describes: '' },
fzbid: item.id,
children: []
})
this.$message.success('新增成功')
}
if (item.children && item.children.length > 0) {
this.getNewTree(item.children)
}
})
return obj
},
这里使用的是递归函数,一层一层往下匹配,当匹配不到时把children当成数组传给方法本身,自身在调用一次,直到匹配到数据,然后使用数组方法push在children下添加数据
删除
// 递归取fzbid
deleteTreeCode(obj, id) {
obj.map((item, index) => {
if (item.id == id) {
this.handleDelete(this.treeList, item.fzbid, item.id)
}
if (item.children && item.children.length > 0) {
this.deleteTreeCode(item.children, id)
}
})
return obj
},
// 递归删除节点
handleDelete(obj, fzbid, id) {
obj.map((item) => {
if (item.id == fzbid) {
console.log(item.children.length, 789);
for (let v = 0; v < item.children.length; v++) {
if (item.children[v].id == id) {
console.log(v.id, id);
item.children.splice(v, 1)
this.$message.success('删除成功')
this.handleTreeInfo()
}
}
} else if (fzbid == 1) {
this.treeList = []
this.$message.success('删除成功')
this.handleTreeInfo()
}
if (item.children && item.children.length > 0) {
this.handleDelete(item.children, fzbid, id)
}
})
return obj
},
因为我这里的需求是删除的时候点击的节点也需要删除,思路就是获取到点击节点的父id通过父id去查找节点的父级把children置空就能实现删除,这里接口返回的父id字段是fzbid
修改
// 指标树节点打开弹框
onClick(v, data, type) {
this.addId = data.id
this.drawer = true
this.type = type
if (type == 2) {
this.form.name = data.zbname
this.form.region = data.bzValue
}
},
修改时需要先回显数据,打开弹窗的时候判断状态,1是新增2是修改,修改时给v-model赋值
// 新增指标树节点提交数据
onSubmit() {
if (this.type == 1) {
console.log(this.getNewTree(this.treeList), "新增成功");/* 新增 */
this.handleTreeInfo()
} else {
console.log(this.onEdit(this.treeList), "修改成功"); /* 修改 */
}
this.drawer = false/* 关闭弹窗 */
},
// 修改指标树
onEdit(obj) {
obj.map((item, index) => {
if (item.id == this.addId) {
// item.zbname = this.form.name
this.zbList.map(v => {
console.log(v.id, "iddd", this.form.name);
if (v.id == this.form.name) {
item.zbname = this.treeName
item.bzValue = this.form.region
item.zbid = this.zbid
}
})
this.$message.success('修改成功')
this.handleTreeInfo()
}
if (item.children && item.children.length > 0) {
this.onEdit(item.children)
}
})
return obj
},