[Vuejs]-How can I abstract the following pattern? (using Vue.js)

0👍

Finally figured it out. I used the folder-tree example from the Vue.js documentation to guide me. Here are the templates and html:

<template id="menu-template">
  <div>
  <div>{{menu.name}}
    <span v-if="menu.options.length > 0" v-on:mouseenter="showOptions = !showOptions">&gt;&gt;</span>
    <span v-else v-on:click="selectOption">OK</span>
  </div>
  <menu-children :options="menu.options" v-if="showOptions" v-on:went-out="showOptions = !showOptions"></menu-children>
  </div>
</template>  
<template id="menu-options-template">
  <ul class="list" v-on:mouseleave="sendUp">
    <li v-for="choice in options">
      <amenu-parent v-if="choice.options" :menu="choice"></amenu-parent>
      <span v-else>{{ choice.name }}</span>
    </li>
  </ul>
</template>

<div id="app">
  <div v-for="r in root">
    <amenu-parent :menu="r"></amenu-parent>
  </div>
</div>

and here is the js:

Vue.component('amenu-parent', {
  template: "#menu-template",
  props: ['menu'],
  data: function() {
    return {
      showOptions: false,
    }
  },
  methods: {
    selectOption: function(v) {
      alert('clicked');
    }
  }
});
Vue.component('menu-children', {
  template: "#menu-options-template",
  props: ['options'],
  methods: {
    sendUp: function() {
      this.$emit("went-out");
    }

  }
});

var app = new Vue({
  el: "#app",
  data: {
    root: [{
      name: 'a',
      options: [{
        name: '1',
        options: []
      }, {
        name: 'asdf',
        options: [{
          name: 'deep',
          options: []
        }]
      }]
    }, {
      name: 'number2',
      options: [{
        name: 'deep',
        options: []
      }]
    }]
  },
});

And some css:

body {
  font-size:1.8em;
}
.list > li {
  background-color:#EEE;
  width:300px;
}

Leave a comment