JSFiddle - React, Tailwind, and code Playground

by Md. Atiquzzaman Soikat

HTML

<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<!-- item template -->
<script type="text/x-template" id="item-template">
  <li>
    <div
      :class="{bold: isFolder}"
      @click="toggle"
      @dblclick="changeType">
      {{model.name}}
      <span v-if="isFolder">[{{open ? '-' : '+'}}]</span>
    </div>
    <ul v-show="open" v-if="isFolder">
      <item
        class="item"
        v-for="model in modelData.children"
        :model="model" :key="model.id">
      </item>
      <li class="add" @click="addChild">+</li>
    </ul>
  </li>
</script>

<p>(You can double click on an item to turn it into a folder.)</p>

<!-- the demo root element -->
<ul id="demo">
  <item
    class="item"
    :model="nestedInformation[1]">
  </item>
</ul>

CSS

body {
  font-family: Menlo, Consolas, monospace;
  color: #444;
}
.item {
  cursor: pointer;
}
.bold {
  font-weight: bold;
}
ul {
  padding-left: 1em;
  line-height: 1.5em;
  list-style-type: dot;
}

JavaScript

var data2 = [{
    "id": 1,
    "name":"games",
    "parentid": null
  },
  {
    "id": 2,
    "name": "movies",
    "parentid": null
  },
  {
  	"name": "iron-man",
    "id": 3,
    "parentid": 2
  },
  {
    "id": 4,
    "name": "iron-woman",
    "parentid": 3
  }
]

// define the item component
Vue.component('item', {
  template: '#item-template',
  props: {
    model: Object
  },
  data: function () {
    return {
      open: false,
      modelData: this.model
    }
  },
  computed: {
    isFolder: function () {
      return this.model.children &&
        this.model.children.length
    }
  },
  methods: {
    toggle: function () {
      if (this.isFolder) {
        this.open = !this.open
      }
    },
    changeType: function () {
      if (!this.isFolder) {
        Vue.set(this.model, 'children', [])
        this.addChild()
        this.open = true
      }
    },
    addChild: function () {
    	var model = this.modelData;
    	model.children = Object.assign({}, this.modelData.children, {
        name: 'My Tres',
 				children: [
    			{ name: 'hello' },
    			{ name: 'wat' }
        ]
      });
      this.modelData = Object.assign({}, model);
    }
  }
})

// boot up the demo
var demo = new Vue({
  el: '#demo',
  data: {
    treeData2: data2
  },
  computed: {
   nestedInformation: function () {
   					console.log(this.nestInformation(data2));
            return this.nestInformation(data2);
        }
  
  },
  methods:{
        nestInformation: function(arr, parent){  
           var out = []
    for(var i in arr) {
        if(arr[i].parentid == parent) {
            var children = this.nestInformation(arr, arr[i].id)

            if(children.length) {
                arr[i].children = children
            }
            out.push(arr[i])
        }
    }
    return out
    }
    }
})