【问题标题】:Show Bootstrap4 modal without Jquery in VueJS在 VueJS 中显示没有 Jquery 的 Bootstrap4 模态
【发布时间】:2020-09-28 02:53:09
【问题描述】:
我正在尝试从 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>
【问题讨论】:
标签:
javascript
twitter-bootstrap
vue.js
bootstrap-4
bootstrap-modal
【解决方案1】:
当您希望引导模态时如何使用 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>
codesandbox demo
希望对你有帮助