Vue-Multiselect Multiple Select Able To Reselect Selected Item

Viewed 261

Using Vue-Multiselect library with multiple selections enabled, is it possible to reselect the selected item/s? Let's say there are two options Product 1 and Product 2:

options: [
    { name: 'Product 1', value: 'product_1' },
    { name: 'Product 2', value: 'product_2' }
]

Then I will select Product 1 multiple times so the result would be:

[
  {
    "name": "Product 1",
    "value": "product_1"
  },
  {
    "name": "Product 1",
    "value": "product_1"
  }
]

It would be something like:

enter image description here

How to achieve this behavior?

PS I'm open to using other Vue 3 select libraries with multiple items and duplication of selected items.

2 Answers

As @mamdasan said, To achieve this requirement you can listen to @input event which emitted after v-model value changes. To get the duplicate selected options you can maintain a separate array and empty the v-model variable while listening to @input event.

Note : I am facing one challenge while working on this requirement is to display the chips on selection as v-model value got empty.

Demo :

var app = new Vue({
  el: '#app',
  components: { Multiselect: window.VueMultiselect.default },
  data () {
    return {
      value: [],
      selectedItems: [],
      options: [
                 {
                   "city": "San Martin"
                 },
                 {
                   "city": "San Nicolas"
                 },
                 {
                   "city": "San Francisco"
                 }
               ]
    }
  },
  methods: {
    onSelect() {
  this.selectedItems.push(this.value[0]);
      this.value = [];
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/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">
  <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<div id="app">
<div>
  <multiselect
    v-model="value"
    placeholder="Select City"
    label="city"
    :options="options"
    :multiple="true"
    :close-on-select="false"
    @input="onSelect"
  >
  </multiselect>
</div>
<pre class="language-json"><code>{{ selectedItems }}</code></pre>
</div>

first listen for changes on your multiselect v-model, every time is changes, add the selected item to an array and empty the multiselect v-model object.

then add this slot in your multi-select:

<template slot="selection" slot-scope="{ values, search, isOpen }">
     <span class="multiselect__single" v-if="theTalkedArray"> 
       {{ values.length }} options selected
     </span>
</template>

basically you create an array, every time the user clicks on multiselect, you add to your array and empty the select value again, and then show the selected items to user

Related