vue.jsvue-componentvue-select

How to make a toggle list vue-select?


I need to make sure that when you click on an already active option, it becomes deselect.

<v-select class="form-control" name="language" v-model="language" id="language" :options="['English', 'Polish']" :clearable="false" :searchable="false" :multiple="true" :closeOnSelect="false"></v-select>

Photo Example

I could not find information on this on the Internet and in the documentation, so I hope for your help.


Solution

  • There isn't any built in way or a prop to deselect items for the vue-select package, however there are two ways of going about it:

    1)You can use the (option:selecting) event to filter the array yourself, therby deselecting that option. Checkout the example below.

    <template>
       <div>
          <v-select
             class="form-control"
             name="language"
             v-model="language"
             id="language"
             :options="['English', 'Polish']"
             :clearable="false"
             :searchable="false"
             :multiple="true"
             :closeOnSelect="false"
             @option:selecting="handleDeselect"
          ></v-select>
          <div class="mt-40">Languages is : {{ language }}</div>
       </div>
    </template>
    
    <script>
    import vSelect from "vue-select";
    import "vue-select/dist/vue-select.css";
    export default {
       components: { vSelect },
       data() {
          return {
             language: ["English"],
          };
       },
       methods: {
          handleDeselect(e) {
             // Check if the lagueage array contains the selected element (e)
             // If so, filter the language array
             if (this.language.includes(e)) {
                this.language = this.language.filter((el) => {
                   return el != e;
                });
             }
          },
       },
    };
    </script>
    

    2)Use the vue-multiselect package which offers deselecting out of the box (easiest & my preferred way)