dependent selects with Vue.js

by lmk123

HTML

<script src="https://unpkg.com/dependent-selects@0.1.0"></script>
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    <select v-for="(list, index) in lists" v-model="selected[index]" @change="onChange(index)">
      <option :value="undefined">select one</option>
      <option v-for="option in list" :value="option">
        {{ option.label }}
      </option>
    </select>
  </div>
  <div>
    Max level:
    <input type="number" min="1" v-model="maxLevel">
  </div>
  <div>
    <button @click="setValues">Set value to ['c', 'b']</button>
    <button @click="reset">Reset</button>
  </div>
  <div>
    Selected:
    <pre>{{ beauti }}</pre>
  </div>
</div>

JavaScript

new Vue({
  el: '#app',
  data: function() {
    var that = this
    this.multi = new DependentSelects(function(index) {
      if (index >= that.maxLevel) return
      return new Promise(function(reslove) {
        setTimeout(function() {
          reslove([{
            label: 'label a',
            value: 'value a'
          }, {
            label: 'label b',
            value: 'value b'
          }, {
            label: 'label c',
            value: 'value c'
          }])
        }, Math.random() * 500)
      })
    })
    return {
      maxLevel: 3,
      lists: this.multi.lists,
      selected: this.multi.selected
    }
  },
  methods: {
    onChange: function(index) {
      this.multi.set(index, this.selected[index])
    },
    setValues: function() {
      this.multi.fill(function(index, list) {
        switch (index) {
          case 0:
            return list[2]
          case 1:
            return list[1]
        }
      })
    },
    reset: function() {
      this.multi.reset()
    }
  },
  computed: {
    beauti: function() {
      return JSON.stringify(this.selected, null, 2)
    }
  }
})