DEV Community

Scott
Scott

Posted on

Programmatically Opening Bootstrap Vue Dropdown

The Skinny || TLDR;

  • If you're using Bootstrap Vue's dropdown found here, and you want to programmatically open the dropdown, simply add class="show" when you want the dropdown to be open. The implementation can look something like:
<b-dropdown class="dropdown" :class="{ show: isOpen }"> // thanks psimyn
Enter fullscreen mode Exit fullscreen mode

Sometimes I spend so much time trying to figure out such a what-I-thought to-be-simple problem when building a feature, I feel like its my duty to share it.

Whats the issue?

Well this week I was working on building a feature that involves Bootstrap Vue's dropdown. I built the off click to close the dropdown, did the search thingy I needed to, debounced it, but I COULDN'T OPEN THE DROPDOWN PROGRAMMATICALLY! WHERE ARE THE ANSWERS!!!

The Approach

I looked through the Bootstrap Vue docs and could not find out how to do this anywhere! Stackoverflow...nothing except some recommendations using Jquery, which I really didn't want to do. Long story..don't ask.

AHA!

Let's go to bootstraps docs, cause Bootstrap Vue is built off of Bootstrap. Of course! This must be the way, or la manera in Spanish ;)

The Solution

Conditionally add the class show to the dropdown.

Hope you enjoyed reading! Read more from me @ https://scottistern.com!

Resources

Top comments (3)

Collapse
 
itachiuchiha profile image
Itachi Uchiha • Edited

You can use refs. For example;

<div>
  <b-button size="sm" @click="toggle">
    Toggle Dropdown
  </b-button>
  <b-dropdown ref="dropdown" id="dropdown-1" text="Dropdown Button" class="m-md-2">
    <b-dropdown-item>First Action</b-dropdown-item>
    <b-dropdown-item>Second Action</b-dropdown-item>
    <b-dropdown-item>Third Action</b-dropdown-item>
    <b-dropdown-divider></b-dropdown-divider>
    <b-dropdown-item active>Active action</b-dropdown-item>
    <b-dropdown-item disabled>Disabled action</b-dropdown-item>
  </b-dropdown>
</div>

and JavaScript code is like that;

data() {
    return {
      name: 'BootstrapVue',
      show: false
    }
  },
  methods: {
    toggle() {

      this.show = !this.show


      if(!!this.show) this.$refs.dropdown.show();
      else this.$refs.dropdown.hide();

    },
  }

Example

Collapse
 
scottstern06 profile image
Scott

Thank you so much for taking the time to post this.

I must have been using an older version of Bootstrap Vue, because I definitely tried this :)

Collapse
 
aaiing profile image
AAI INGENIERIA • Edited

im trying get id data from b-dropdown list,
example: charge data from graphql client with id and description data.
you have a example? ty!