1

I'm trying to use Bootstrap 5 with Vue (2.x) without any third-party library. The idea is to create a wrapper for each Bootstrap component that I want to use (not all of them).

I use the following SO thread as a basis: Using Bootstrap 5 with Vue 3

The first component I created is bootstrap.Alert. And so far it works flawlessly.

<template>
  <div ref="el" class="alert alert-danger alert-dismissible fade show" role="alert">
    <div>{{ message }}</div>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
</template>

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

export default {
  name: 'BootstrapAlert',
  props: {
    message: {
      type: String,
      default: '',
    },
  },
  created() {
    Alert(this.$refs.el);
  },
  mounted() {
    const { el } = this.$refs;
    [
      'close',
      'closed',
    ].forEach((e) => {
      el.addEventListener(`${e}.bs.alert`, () => {
        this.$emit(e);
      });
    });
  },
};
</script>

The second is bootstrap.Toast, which is a bit problematic:

<template>
  <div ref="el" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-muted">just now</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">See? Just like this.</div>
  </div>
</template>

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

export default {
  name: 'BootstrapToast',
  created() {
    Toast(this.$refs.el);
  },
};
</script>

Although the implantation/code is nearly identical, I always get the following error when rendering the Toast component:

[Vue warn]: Error in created hook: "TypeError: Cannot read property '_getConfig' of undefined"

And if I try to move the Toast initiation in the mounted event instead of created, I receive a different error:

[Vue warn]: Error in mounted hook: "TypeError: Cannot set property '_element' of undefined"

Anyone has any idea what went wrong?

Thanks in advance!

=== WORKING SOLUTION ===

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

export default {
  name: 'BootstrapToast',
  data() {
    return {
      toast: null,
    };
  },
  mounted() {
    this.toast = new Toast(this.$refs.el);
    this.toast.show();
  },
};
</script>

1 Answer 1

1

You need to use new Toast(..) to initiate the Toast, and make sure it's in the mounted() hook...

   mounted() {
        var toast = new Toast(this.$refs.el)
        toast.show()
   },

Codeply

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.