写完(一)之后,又忙了一段,今天有点空闲时间,还是对这个进行一个梳理,记录。
首先,说一下,自己对于tree结果的理解,用vue的核心就说对数据的操作。那么对于tree结构,就是对于复杂,嵌套数据的操作,一般会用到递归。
一、写一下官网对于新增和删除的方法。
append(data) { const newChild = { id: id++, label: 'testtest', children: [] }; if (!data.children) { this.$set(data, 'children', []); } data.children.push(newChild); }, remove(node, data) { const parent = node.parent; const children = parent.data.children || parent.data; const index = children.findIndex(d => d.id === data.id); children.splice(index, 1); },
新增的话就将,你想要添加的数据,赋给newChild就ok了。
二、节点的修改
修改的话,就是通过右键点击的时候,拿到当前节点的数据,做一个数据回显,其他和新加一样。
三、实现节点上下移动
右键选择节点,弹出菜单,选中上移进行上移操作。这里需要说一下,本人具体开发的时候,最开始想用官网给的新增和删除模式来写,但是遇到点问题。就按着自己的办法写的,但是现在回想起来,仿照官网的格式,应该也是可以实现的。
这是上移和下移的方法。就是一个递归的使用
move(arr, el) { // //上移动 arr.forEach((i, idx) => { if (i.name == el.name) { if (idx == 0) { this.$message.error("已经到顶了"); return false; } else { arr[idx] = arr.splice(idx - 1, 1, arr[idx])[0]; return; } } else { if (i.children) { this.move(i.children, el); } } }); return arr; }, moveDoen(arr, el) { this.downData = ""; arr.forEach((i, idx) => { if (this.downData == 1) { return; } else { if (i.name == el.name) { if (idx == arr.length - 1) { this.$message.error("已经到底了"); return false; } else { arr.splice(idx, 1, ...arr.splice(idx + 1, 1, arr[idx])); return (this.downData = 1); } } else { if (i.children) { this.moveDoen(i.children, el); } } } }); return arr; },
菜单上的操作代码
else if (key == 4) { let data = this.nodedata; let node = this.Node; let datas = this.move(this.data, data, key); this.data.splice(0, 1, datas[0]); this.data = JSON.parse(JSON.stringify(this.data)); } else if (key == 5) { let data = this.nodedata; let node = this.Node; let datadoem = this.moveDoen(this.data, data); this.data.splice(0, 1, datadoem[0]); this.data = JSON.parse(JSON.stringify(this.data)); }
后记:
可能最开始没有太注意,官网上的实例吧,也没有给注释,导致没按着这个模式写,出现了问题,排查了很久的bug。最后弄明白了,排查的时候,我发现数据已经改了,tree的数据已经发生了改变,但是视图没有渲染,首先我就尝试了this.$set去写改变的数据,但是还是没有效果。然后再去看官网,看社区,突然发现,官网上是这样写的JSON.parse(JSON.stringify(data)),就解决了。发生这种情况的原因是,vue多层数据嵌套的bug的问题。
return { data: JSON.parse(JSON.stringify(data)), data: JSON.parse(JSON.stringify(data)) }