I have a v-treeview
on the left, and the JSON
data the treeview uses displayed on the right. When creating root child nodes, the treeview updates correctly. However, when adding a child node under the root (you can see the object correctly updates on the right), the treeview does not automatically capture that and render a child under the root element.
When updating the object data, the entire object that the treeview references gets rebuilt, so there should not be a circumstance where array manipulation becomes an issue. I am not simply doing a push
on a child.
Is there any way around this? Using this.$forceUpdate()
also does not work.
So far, the only very hacky solution is to set the array to []
, then set it to the data after a timeout
this.treeViewData= []
setTimeout(() => {
this.treeViewData = realData
this.busy = false
}, 400)
But that's not great
The folder structure is just a flat array:
fileTree: [
{
id: 1,
parentId: null,
folderName: 'My Documents'
},
{
id: 2,
parentId: 1,
folderName: 'Root Folder 1'
},
{
id: 3,
parentId: 1,
folderName: 'Root Folder 2'
},
{
id: 4,
parentId: 2,
folderName: 'Child 1 of Root Folder 1'
},
{
id: 5,
parentId: 2,
folderName: 'Child 2 of Root Folder 1'
},
]
Which gets converted to the tree object on every change using:
getFolderStructure() {
const idMapping = this.fileTree.reduce((acc, el, i) => {
acc[el.id] = i
return acc
}, {})
let root = {}
for (const el of this.fileTree) {
el.children = []
if (el.parentId === null) {
root = el
continue
}
// Use our mapping to locate the parent element in our data array
const parentEl = this.fileTree[idMapping[el.parentId]]
// Add our current el to its parent's `children` array
parentEl.children = [...(parentEl.children || []), el]
}
this.folderStructure = {}
this.folderStructureChildren = []
setTimeout(() => {
this.folderStructure = root
this.folderStructureChildren = root.children
}, 10)
},
So, when adding a new folder, I just add a new object to the array (with whatever parent ID I want), and that gets generated to the object.
For completeness sake, I followed this tutorial: https://typeofnan.dev/an-easy-way-to-build-a-tree-with-object-references/