寫完(一)之后,又忙了一段,今天有點空閑時間,還是對這個進行一個梳理,記錄。
首先,說一下,自己對於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)) }