[Vuejs]-How to display treeview component in vuetify

1👍

<v-treeview/>, by default, loads the ‘children’ property, if there’s any. However, on your example, we can see that on the first children, it has no ‘children’ property. But ‘parent’ property is present, and you want to treat it as a children too.

Solution: You can create a computed variable that traverses all nodes, check if it has a ‘parent’ property, and add ‘children’ property that has the same value as the ‘parent’ property. (I’m gonna use this solution here for traversing the items).

<v-treeview :items="modifiedItems"/>
data: () => ({
  items: [{...}]
}),

computed: {
  modfiedItems() {
    // let's clone the items so we won't pollute the original data.
    const clonedItems = JSON.parse(JSON.stringify(this.items));
    this.traverse(clonedItems);
    return clonedItems;
  }
},
methods: {
  // reference: https://stackoverflow.com/a/722676/9183405
  traverse(items) {
    // check if the node is an object or array
    if (items !== null && typeof items === "object") {
      Object.entries(items).forEach(([key, value]) => {
        // check if the item/node has a 'parent' property
        if (key === "parent") {
          items.children = value; 
        }
        this.traverse(value);
      });
    }
  }
}

enter image description here

So now, if the a node/item has a ‘children’ or ‘parent’ property to it, it will still be loaded on the treeview. If both property is present, the ‘children’ will be the one used.

Here is a sample code demo.

Leave a comment