Home > Enterprise >  How to trigger bootstrap-vue dropdown from outside element?
How to trigger bootstrap-vue dropdown from outside element?

Time:12-26

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 ?

CodePudding user response:

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/[email protected]/dist/css/bootstrap.min.css" />
<script src="//unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="//unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>


<div id="app" >
  <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>

  • Related