0

Following up on my old thread Vue.js (2.x) with Bootstrap 5

I keep having issues when creating a bootstrap component wrapper in Vue. The idea is to create a wrapper for each Bootstrap component that I want to use (not all of them).

The issue happened when I tried to create a bootstrap.Dropdown wrapper. The dropdown menu is shown properly when clicked, but it didn't auto-close when clicking outside (somewhere else).

<template>
  <div ref="el" class="dropdown">
    <button
      class="btn btn-primary dropdown-toggle"
      type="button"
      data-bs-toggle="dropdown"
      aria-expanded="false"
    >
      Select...
    </button>
    <ul class="dropdown-menu">
      <slot></slot>
    </ul>
  </div>
</template>

<script>
import { Dropdown } from 'bootstrap';

export default {
  name: 'BootstrapDropdown',
  data() {
    return {
      dropdown: null,
    };
  },
  mounted() {
    const { el } = this.$refs;

    this.dropdown = new Dropdown(el, {
      autoClose: true,
    });

    ['show', 'shown', 'hide', 'hidden'].forEach((e) => {
      el.addEventListener(`${e}.bs.dropdown`, () => {
        this.$emit(e);
      });
    });
  },
};
</script>

Any ideas are welcomed. Thanks in advance.

GoldenAxe
  • 15
  • 1
  • 4

1 Answers1

0

I think it's not working because the Dropdown instance needs to be set on the trigger element, not the container. Change the "el" ref to the trigger button...

<template>
  <div class="dropdown">
    <button
      ref="el" 
      class="btn btn-primary dropdown-toggle"
      type="button"
      data-bs-toggle="dropdown"
      aria-expanded="false"
    >
      Select...
    </button>
    <ul class="dropdown-menu">
      <slot></slot>
    </ul>
  </div>
</template>

Demo

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624