javascript - 在 VueJS 中显示没有 Jquery 的 Bootstrap4 模态
问题描述
我正在尝试从 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>
希望这可以帮到你
推荐阅读
- mongodb - 如何下载使用 GridFS 存储并在 React/Javascript 客户端中使用 GraphQL 返回的文件?
- unity3d - 为什么我的 Unity photon Pun2 导入不起作用?
- r - R Shiny:将用户上传的文件上传到 AWS S3 服务器
- networking - 如何计算编码的 Base64 消息
- firebase - Firebase 分析 cookie 不安全
- javascript - 如何使用 rollup.js 将提取的 css 文件正确注入 html 文件的头部?
- android-studio - 在布局文件中发现意外的文本:“android:background="#AA00FF">”
- c++ - 在 Unix 中从串口读取时输入/输出错误
- python - 如何从列表python中删除唯一元素并保留一个重复?
- google-sheets - 使用过滤器和数组组合多个条件