When exploring how to implement a bootstrap modal with jquery, you will notice that they apply a show class to the modal and switch the style of the modal from style="display: none"
to style="display:block"
In addition, a div
<div class="modal-backdrop fade show"></div>
is appended to the body, creating a black overlay background behind the modal.
You can achieve this by coding something similar to the following:
<template>
<div>
<button type="button" class="btn btn-primary" @click="toggleModal">Open Modal</button>
<div
ref="modal"
class="modal fade"
:class="{show, 'd-block': active}"
tabindex="-1"
role="dialog"
>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
@click="toggleModal"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
</div>
</div>
</div>
<div v-if="active" class="modal-backdrop fade show"></div>
</div>
</template>
<script>
export default {
data() {
return {
active: false,
show: false
};
},
methods: {
/**
* When the button in bootstrap modal is clicked,
* the modal display property changes and a show class is added.
* To achieve this effect, we display the modal backdrop and set the modal's display property to block.
* Then, we add the show class to the modal using setTimeout after showing the modal backdrop and changing the display property
* This helps in making the modal animation work smoothly
*/
toggleModal() {
const body = document.querySelector("body");
this.active = !this.active;
this.active
? body.classList.add("modal-open")
: body.classList.remove("modal-open");
setTimeout(() => (this.show = !this.show), 10);
}
}
};
</script>
Check out the codesandbox demo for reference
I hope this explanation proves helpful for you!