'How to open a select dropdown on hover using Bootstrap Vue

I need a way to trigger the <select> or <b-form-select> and display the list of dropdown options on mouse hover. Without using JQuery or any external plugin other than Vue.js.



Solution 1:[1]

As per my understanding you want to show/hide the <b-form-select> on mouseover and mouseleave event. If Yes, I have few suggestions :

  • Use a div as a wrapper which will trigger the mouseover and mouseleave events. We can directly trigger the mouse events by appending the native in the itself but once it will hide, there will be no way to get the dropdown back on mouseover again.
  • You can simply show/hide the dropdown via v-show directive. We can easily set the value from our mouse events.

Working Demo :

new Vue({
  el: '#app',
  data() {
    return {
      selected: null,
      isVisible: true,
      options: [
        { value: null, text: 'Please select an option' },
        { value: 'a', text: 'This is First option' },
        { value: 'b', text: 'Selected Option' },
        { value: { C: '3PO' }, text: 'This is an option with object value' },
        { value: 'd', text: 'This one is disabled', disabled: true }
      ]
    }
  },
  methods: {
    onOver() {
      this.isVisible = true;
    },
    onLeave() {
      this.isVisible = false;
    }
  }
})
.wrapper-div {
  height: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css"/>
<div id="app">
  <div class="wrapper-div" @mouseover="onOver" @mouseleave="onLeave">
    <b-form-select
                   v-model="selected"
                   :options="options"
                   v-show="isVisible">
    </b-form-select>
  </div>
</div>

Solution 2:[2]

The effect of this solution is similar to opening the select by clicking on it (although, not the same ...)

<template>
  <select ref="mySelect" @mouseenter="hover(true)" @mouseleave="hover(false)" :size="size">
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
  </select>
</template>

<script>
import {ref} from 'vue';
export default {
  name: "Test",
  setup(){
    const mySelect = ref();
    const size = ref('0');
    return {mySelect, size}
  },
  methods: {
    hover(val) {
      this.size = val ? this.mySelect.length.toFixed(0) : '0';
    }
  }
}
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nechoj