1

I'm trying to open a Vue-Bootstrap dropdown (b-dropdown) pragmatically when I focus on an input (b-form-input field). I have called a @focus method on b-form-input to open the dropdown.

Here's My Bootstrap Code:

<b-form-input v-model="search" @focus.native="openDropdown"></b-form-input>

<b-dropdown id="ddown1" text="Dropdown Button" class="m-md-2" ref="dropdownRef">
 <b-dropdown-item>First Action</b-dropdown-item>
 <b-dropdown-item>Second Action</b-dropdown-item>
</b-dropdown>

Here's my Vuejs code:

methods:{

   openDropdown(){
    const elem = this.$refs.dropdownRef;
    elem.click();
   }

}

I have tried many methods like setting elem.visible =true. But it quickly opens and then closes.

I have followed How to open Bootstrap dropdown programmatically . But it doesn't apply to vue-bootstrap.

thar
  • 13
  • 3

1 Answers1

-2

You can use jQuery to toggle dropdown

methods:{
   openDropdown() {
    $('#ddown1').dropdown('toggle');
   }
}

new Vue({
  el:'#app',
  data () {
    return {
      search: ''  
    }
  },
  methods:{

   openDropdown() {
    console.log('open');
    $('#ddown1').dropdown('toggle');
   }

}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<link href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" rel="stylesheet"/>
<link href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>

<div id="app">
    <b-form-input v-model="search" @focus.native="openDropdown"></b-form-input>

<b-dropdown id="ddown1" text="Dropdown Button" class="m-md-2 active" ref="dropdownRef">
 <b-dropdown-item>First Action</b-dropdown-item>
 <b-dropdown-item>Second Action</b-dropdown-item>
</b-dropdown>
</div>

</div>

Check my demo at https://codepen.io/ittus/pen/OZEOGW

ittus
  • 21,730
  • 5
  • 57
  • 57
  • Thanks, your solution works perfectly. But is there a way to approach this without JQuery. As I know VueJS refs were used to getting the references of DOM elements. Is there any way to approach this using VueJS refs ? Of course, I found b-dropdown contains many attributes and methods like visible, click etc. Can't we use one of those attributes to approach the solution? But any of them didn't work for me – thar May 13 '18 at 17:00
  • Never mix JS frameworks for manipulating the DOM – crash springfield Nov 30 '20 at 17:39