I am trying to use Vue3 (Vite) and Bootstrap 5 to create a modal that is called by code. However, when opening the modal from its parent, an error is thrown.
I have bootstrap installed and included:
import bootstrap
(main.js)
import bootstrap/dist/js/bootstrap
does not change anything.
I have created a simple modal that listens for a prop and then opens the modal.
When I open it, the error appears:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'backdrop')
<template>
<div class="modal" tabindex="-1" id="errModal" aria-labelledby="ErrorModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Error {{ this.occurred }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="ErrorModalLabel"></button>
</div>
<div class="modal-body">
<p>{{ this.error_message }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
</template>
<script>
import { Modal } from "bootstrap"
export default {
props: {
occurred: String,
error_message: String,
show: Boolean,
},
components: {
myModal: null
},
data() {
return {
}
},
methods: {
},
mounted() {
this.myModal = new Modal(document.getElementById('errModal'))
},
watch: {
show: function (newVal, oldVal) { // watch it
this.cam_prop = newVal.properties
},
}
};
</script>
Calling from Parent:
<RegIdentErrorModalVue id="#ErrModal" :show="this.error" :occurred="'Identification'" :error_message="this.error_text">
</RegIdentErrorModalVue>
Creating the Modal with new bootstrap.Modal
does not work (bootstrap not defined)
I think the error is importing, but the styling works, could it be Vite?
You are trying to initialize the modal before the DOM is ready. I suggest you initialize the component at the mounted of the parent component. Something like this:
Parent Component
<template>
...
<RegIdentErrorModalVue v-if="isMountedComponent" id="#ErrModal" :show="this.error" :occurred="'Identification'" :error_message="this.error_text" />
...
</template>
<script>
export default {
data() {
return {
isMountedComponent: false,
}
},
mounted() {
this.isMountedComponent = true;
},
}
</script>