Switch vue-multiselect on/off with the click of a button

Upon clicking the button, a multiselect menu pops up. However, on a second click, the true/false values quickly flash and the isOpen status remains true. What could be causing this issue?

Here is the template:

<div id="app">
  <button @click="toggle">open and close later
  </button>
    <pre>{{ isOpen }}</pre>
  <multiselect 
    ref="multiselect"
    v-model="value" 
    :options="options"
    :multiple="true"
    track-by="library"
    :custom-label="customLabel"
    @close="isOpen = false"
    @open="isOpen = true"
    >
  </multiselect>
</div>

This is the JavaScript code:

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    isOpen: false,
    value: { language: 'JavaScript', library: 'Vue-Multiselect' },
    options: [
        {   language: 'JavaScript', library: 'Vue.js' },
      { language: 'JavaScript', library: 'Vue-Multiselect' },
      { language: 'JavaScript', library: 'Vuelidate' }
    ]
    },
  methods: {
    toggle () {
        if (this.isOpen) {
        this.$refs.multiselect.$el.blur();
        this.isOpen = false;
      }
      else {
        this.$refs.multiselect.$el.focus();
        this.isOpen = true;
      }

    }
  }
}).$mount('#app')

You can view the example here: https://jsfiddle.net/46s5aknt/

Answer №1

Upon digging into the source code of this component, it became evident that finding a "legit" way to meet your requirement was not possible. The @blur callback will be triggered regardless of any attempts to control its behavior.

One workaround could involve implementing a locking mechanism with a cooldown period...

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
  blocked: false,
  value: { language: 'JavaScript', library: 'Vue-Multiselect' },
  options: [
    { language: 'JavaScript', library: 'Vue.js' },
    { language: 'JavaScript', library: 'Vue-Multiselect' },
    { language: 'JavaScript', library: 'Vuelidate' }
  ]
},
  methods: {
    toggle () {
      if (!this.blocked) {
        this.$refs.multiselect.toggle();
      }
    },
    block () {
      this.blocked = true;
      setTimeout(() => {
        this.blocked = false;
      }, 200);
    }
  }
}).$mount('#app')

Answer №2

This particular element is still experiencing the same issue. The toggle event is not being controlled properly.

Nevertheless, although not ideal, you can manage the isOpen prop in this way.

data() {
  return {
    displayMenu: true
  }
},
methods: {
  toggleMenu(){
    this.displayMenu = !this.displayMenu;
    this.$refs.dropdown.isOpen = this.displayMenu;
  }
}

<button @click="toggleMenu" />
<Dropdown ref="dropdown" />

Answer №3

The issue at hand is that the VueMultiselect component closes when there is a click detected outside of it.

Therefore, clicking the button on your mouse results in the VueMultiselect closing, and releasing the button actually reopens the VueMultiselect because the isOpen property was set to false in the close event.

This means that the button can only function as an Open button.

Update:

A better solution would be to hide the button when the VueMultiselect is already open.

Answer №4

Although this post may be considered old, I wanted to share a recent discovery of mine. (DISCLAIMER: This method may not be the most conventional approach, but it gets the job done)

I encountered a situation where I needed to "close" a dropdown without clicking away from it.

While exploring the node modules for "vue-multi-select," I came across the option to use refs to call the "closeMultiSelect()" function and successfully close the dropdown.

Below is an illustration of how I wrapped the component in a div to apply an event listener to the entire component:

<div v-on:mouseleave="close()">
<vue-multi-select
    :ref="'multiselect'"
    v-model="selectedGroups"
    :selectOptions="options"
    :options="{multi : true}"
    :btnLabel="() => `Contact Groups`"
    :key="multiSelectComponentKey"
    search
></vue-multi-select>
</div>

Here is how I triggered the method to close the dropdown:

method:{
    close: function(){
        this.refs.multiselect.closeMultiSelect();  // this action closes the dropdown
    }
}

The same methodology applies to opening the dropdown as well:

method:{
    open: function(){
        this.refs.multiselect.openMultiSelect();  // this action opens the dropdown
    }
}

That's all for now. If this information proves helpful to anyone, that's fantastic! Feel free to suggest any improvements or better methods for handling this. Together, we can keep this updated with the best practices.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Check out Vue3's property watching feature`

Currently, I have a form that is being edited and the created method is used to prefill the form information from an api call, which works perfectly fine. However, my goal is to monitor the fields in the form. If any of them are edited, I want to set a va ...

Looking to loop through the JSON objects saved in an array of JSON data in local storage

I have reviewed various resources, including Iterate through nested json object array, but none of them seem to address my specific situation. The current challenge I am facing involves storing multiple JSON objects in an array within local storage. This ...

The message vanishes upon refreshing the page

I've developed a socket.io web app. When I click on the button to send a message, the message appears briefly but disappears when the page refreshes unexpectedly. How can I prevent this random refreshing and ensure that socket.io saves my messages? B ...

What is the best way to prematurely exit an outer function when there are multiple inner non-blocking function calls?

For the purpose of learning, I am working on creating a basic version of async.parallel. The description from the documentation is as follows: parallel(tasks, [callback]) Run the tasks array of functions in parallel, without waiting until the previou ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...

Is there a way to organize a table in ReactJS based on ascending numerical values from a particular column?

I am working with a table that retrieves data from an object called blockInfo: <table> <thead> <tr> <th>Timestamp</th> <th>B ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

Using mqtt in Node.js, an example of creating a client with the syntax mqtt.Client(streamBuilder,

Does anyone have a sample implementation of the mqtt.Client(streamBuilder, options) function they can share? https://github.com/mqttjs/MQTT.js/#mqttclientstreambuilder-options It would be really helpful if you could provide a thorough explanation. ...

Guide to binding input type= 'email' in Knockout.js

My project utilizes KnockoutJS with MVC. I am seeking assistance on determining whether an emailId is valid or invalid. Based on this validation, I need to dynamically enable/disable a button and set an error title for the corresponding textbox. Below is ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

I'm looking to merge the functionality of AngularJS confirm with SweetAlert (Swal)

I am currently working on a project and I need to implement a confirmation prompt for the logout functionality. I want to use Sweet Alert for this purpose. While I have found solutions for both the confirmation and Sweet Alert separately, I am struggling t ...

How can I design an SVG page similar to Coin360 and Market Maps?

I need to design a homepage similar to coin360.com, where I can display market maps and cryptocurrency rates. This page will be created using SVG elements for the answers section. Is there a pre-made template available for this design, or can someone gui ...

New techniques in VueJS 3: managing value changes without using watchers

I am currently working on coding a table with pagination components and I have implemented multiple v-models along with the use of watch on these variables to fetch data. Whenever the perPage value is updated, I need to reset the page value to 1. However, ...

Implementing custom styles in JavaScript according to the specific browser or platform

When it comes to adding multiple css styles to a dom element and ensuring compatibility across different browsers, which approach is more optimal for performance? Combining all prefixed css properties together, allowing the browser to decide which one ...

Reduce the size of the object to improve its readability

My JavaScript object is quite lengthy with over 6000 lines, and I am looking to enhance its readability. In the structure below, you'll notice that there are some common elements shared across all environments ('commonA', 'commonB' ...

Is there a way to automatically clear the text field value after submitting?

Greetings everyone, I'm looking for guidance on removing the text field content once I click submit. I have a button labeled "senden" and my goal is to clear the text fields and uncheck the checkbox after clicking this button. I've attempted se ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

JavaScript code to enforce a 100% page zoom setting

After developing a small game in Canvas, I encountered an issue. Some users with their default zoom level set to something other than 100% are unable to view the entire game page. I attempted to resolve this by using the following CSS: zoom: 100%; This ...