Search code examples
vue.jsvuejs2vue-componentvuexvuetify.js

How to display treeview component in vuetify


Can someone help me with render a treeview in vuetify im have a response as like this in this situation im using a vuetify framework

[
  {
    "id": 4,
    "name": "Test",
    "parent_id": 0,
    "image": "gVtHmE4tN18Y.png",
    "children": [
      {
        "id": 6,
        "name": "Test2",
        "parent_id": 4,
        "image": "XBpqGq6CinOm.png",
        "parent": [
          {
            "id": 7,
            "name": "Test3",
            "parent_id": 6,
            "image": "MNI3TmNXI1V5.png",
          }
        ]
      }
    ]
  }
]

and i dont know how display this response in treeview im try to use many solutions but im dont have any result This is what i found out is if someone know how to do this it will be nice thanks for help


Solution

  • <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.