Search code examples
vue.jsbootstrap-vue

How to trigger bootstrap-vue dropdown from outside element?


I'm trying to open bootstrap-vue dropdown from a outside button. For instance:

 <b-dropdown>
    <template #button-content>
      Custom <strong>Content</strong> with <em>HTML</em> via Slot
    </template>
    <b-dropdown-item href="#">An item</b-dropdown-item>
    <b-dropdown-item href="#">Another item</b-dropdown-item>
  </b-dropdown>

<b-button @click="openDropdown">Open Dropdown</b-button> 

<script>
methods: {
 openDropdown(){
   // do something
 }
}
</script>

I see a similar discussion here. But none of them are working. Any update of it or any other method ?


Solution

  • The PR you linked added show and hide methods which can be accessed by adding a ref to the <b-dropdown>, and then referencing this ref in your method.

    <b-dropdown ref="myDropdown"></b-dropdown>
    
    openDropdown() {
      this.$refs.myDropdown.show();
    }
    

    Working Example

    new Vue({
      el: "#app",
      methods: {
        openDropdown() {
          this.$refs.myDropdown?.show();
        }
      }
    });
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
    <script src="//unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="//unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
    
    
    <div id="app" class="p-4">
      <b-dropdown ref="myDropdown">
        <template #button-content>
          Custom <strong>Content</strong> with <em>HTML</em> via Slot
        </template>
        <b-dropdown-item href="#">An item</b-dropdown-item>
        <b-dropdown-item href="#">Another item</b-dropdown-item>
      </b-dropdown>
    
      <b-button @click="openDropdown">Open Dropdown</b-button>
    </div>