[Vuejs]-Single select vue js multiselect sub groups

0👍

You could try something like this below, it’s a bit overly complicated for what it does, but could work well in its own component.

Basically on the input event you can search to see if there are any others in that group and then select accordingly.

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  methods: {
    selectUnique(ev) {
      if (!ev || ev.length < this.value.length) {
        this.value = ev;
        return;
      }

      let newValue = ev.filter(x => this.value.indexOf(x) === -1)[0];
      let group = this.getGroupByLib(newValue);
      if (this.value.some(x => this.getGroupByLib(x) === group)) {
        this.value = this.value.filter(x => this.getGroupByLib(x) !== group);
        this.value.push(newValue);
      } else
        this.value = ev;
    },
    getGroupByLib(lib) {
      return this.options.filter(x => x.libs.some(y => y.name === lib.name))[0].language;
    }
  },
  data() {
    return {

      options: [{
          language: 'Javascript',
          libs: [{
              name: 'Vue.js',
              category: 'Front-end'
            },
            {
              name: 'Adonis',
              category: 'Backend'
            }
          ]
        },
        {
          language: 'Ruby',
          libs: [{
              name: 'Rails',
              category: 'Backend'
            },
            {
              name: 'Sinatra',
              category: 'Backend'
            }
          ]
        },
        {
          language: 'Other',
          libs: [{
              name: 'Laravel',
              category: 'Backend'
            },
            {
              name: 'Phoenix',
              category: 'Backend'
            }
          ]
        }
      ],
      value: []
    }
  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-multiselect@2.1.0"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">
<div id="app">
  <label class="typo__label">Groups</label>
  <multiselect :value="value" :options="options" :multiple="true" group-values="libs" group-label="language" placeholder="Type to search" track-by="name" label="name" @input="selectUnique">
    <span slot="noResult">Oops! No elements found. Consider changing the search query.</span>
  </multiselect>
  <pre class="language-json"><code>{{ value  }}</code></pre>
</div>

0👍

Make these two things into false

 :multiple="false"  :group-select="false"

Check Here Code

Leave a comment