[Vuejs]-Get details of specific node of a tree using vuejs

0👍

You can use a recursive component, see: https://v2.vuejs.org/v2/guide/components-edge-cases.html#Recursive-Components

Here is a simple example based on your data:

const Node = {
  name: 'node',
  template: `
    <div>
        <a @click="$emit('input', value.files)">
        {{ value.name }}
      </a>
      <node v-if="value.children" v-for="child in value.children" :key="child.id" :value="child" @input="$emit('input', $event)"/>
    </div>
  `,
  props: ['value']
};

new Vue({
  el: '#app',
  components: {
    Node
  },
  data() {
    return {
      tree: {
        id: 0,
        name: 'Root',
        files: [],
        children: [{
            id: 1,
            name: 'Resources',
            type: 'folder',
            files: [],
            children: [{
              id: 4,
              name: 'Resources Zone 1-A',
              type: 'folder',
              files: [
                'Resources-zone-east.doc',
                'Resources-zone-east-1-A.doc'
              ]
            }]
          },
          {
            id: 2,
            name: 'Services',
            type: 'folder',
            files: [
              'Services-east-zone-2A.doc',
              'Services-West-zone-2A.doc'
            ],
            children: [{
              id: 5,
              name: 'Services-South-Zone-3B',
              type: 'folder',
              files: [
                'Services-South-zone-3B1.doc',
                'Services-South-zone-3B2.doc'
              ]
            }]
          },
          {
            id: 3,
            name: 'Servers',
            type: 'folder',
            files: [
              'Servers-east-zone-3B.doc',
              'Servers-west-zone-3B.doc'
            ],
            children: []
          }
        ]
      }
    };
  },
  methods: {
    log(value) {
      console.log(value);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <node :value="tree" @input="log"></node>
</div>

This is a basic tree structure. The node component reference itself to iter over its children. The input event bubbles up to the root instance.

Leave a comment