简体   繁体   中英

Vue.js (2.x) with Bootstrap 5

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM