Vue.JS tree with data bus

by Alan Grainger

HTML

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

<p>Double click on an item to turn it into a folder.</p>
<p>Right-click on an item to output that model object in the console.</p>
<!-- the demo root element -->
<div id="demo">
  <p style="color:blue">{{ message }}&nbsp;</p>
  <ul>
    <item
      @bus="bus"
      class="item"
      :model="treeData">
    </item>
  </ul>
</div>

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

// demo data
var data = {
  name: 'My Tree',
  children: [
    { name: 'hello' },
    { name: 'wat' },
    {
      name: 'child folder',
      children: [
        {
          name: 'child folder',
          children: [
            { name: 'hello' },
            { name: 'wat' }
          ]
        },
        { name: 'hello' },
        { name: 'wat' },
        {
          name: 'child folder',
          children: [
            { name: 'hello' },
            { name: 'wat' }
          ]
        }
      ]
    }
  ]
}

// define the item component
Vue.component('item', {
  template: '#item-template',
  props: {
    model: Object
  },
  data: function () {
    return {
      open: false
    }
  },
  computed: {
    isFolder: function () {
      return this.model.children &&
        this.model.children.length
    }
  },
  methods: {
    bus: function (data) {
        this.$emit('bus', data)
    },
    contextMenu: function () {
    	this.$emit('bus', this.model)
    },
    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 () {
      this.model.children.push({
        name: 'new stuff'
      })
    }
  }
})

// boot up the demo
var demo = new Vue({
  el: '#demo',
  data: {
    treeData: data,
    message: ''
  },
  methods: {
  	bus: function (data) {
    	console.log(data)
      this.message = 'You right-clicked on ' + data.name
    }
  }
})