我正在尝试从VueJS中的函数显示引导模态。我基本上是在寻找这样做的香草JS方式:$('#myModal')。modal(“ show”)。有多种方法可以使用BootstrapVue进行此操作,但是我当前正在使用的项目不使用bootstrapVue,而仅使用标准bootstrap4。
//component.vue
<template>
<div>
<button type="button" class="btn btn-primary">My Modal</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
...
</div>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
buttonClick() {
// Need to display modal in here
//$('#myModal').modal("show")
}
}
};
</script>
[当您希望引导模式时,如何与jquery一起使用您会发现他们将展示类添加到模式中并更改了样式从style="display: none"
到style="display:block"
和div <div class="modal-backdrop fade show"></div>
附加到主体并且此div是模态后面的黑色叠加背景
因此,您可以执行以下操作:
<template>
<div>
<button type="button" class="btn btn-primary" @click="toggleModal">My 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 clicking on button in bootstrap
* the modal style set to display and after that a show class add to modal
* so to do that we will show modal-backdrop and set modal display to block
* then after that we will add show class to the modal and we will use setTimeout
* to add show class because we want show class to add after the modal-backdrop show and modal display change
* to make modal animation work
*
*/
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>
希望这可以帮助您