[英]Vue.js open modal by click of a button
How to use a button to show the modal in other components?如何使用按钮在其他组件中显示模态? For example, I have the following components:
例如,我有以下组件:
info.vue信息.vue
<template>
<div class="container">
<button class="btn btn-info" @click="showModal">show modal</button>
<example-modal></example-modal>
</div>
</template>
<script>
import exampleModal from './exampleModal.vue'
export default {
methods: {
showModal () {
// how to show the modal
}
},
components:{
"example-modal":exampleModal
}
}
</script>
exampleModal.vue示例Modal.vue
<template>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
hihi
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</template>
How to show the modal from exampleModal.vue?如何从exampleModal.vue 显示模态? I know that I can use data-toggle and data-target to show the modal, like this:
我知道我可以使用 data-toggle 和 data-target 来显示模态,如下所示:
<button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>
But is there any way to show the modal by using the method "showModal"?但是有没有办法使用“showModal”方法来显示模态?
According to your snippet, you're using a classic Bootstrap modal.根据您的代码段,您使用的是经典的 Bootstrap 模式。 You just need to use
data-toggle
and data-target
attributes in that case:在这种情况下,您只需要使用
data-toggle
和data-target
属性:
<div id="app">
<div class="container">
<button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>
<example-modal></example-modal>
</div>
</div>
I misread the question so i edit my answer.我误读了这个问题,所以我编辑了我的答案。
It's possible to open the modal with a custom method.可以使用自定义方法打开模态。 You just need to find the element "#exampleModal" by using
refs
and then open the modal with a bootstrap method ( Bootstrap Programmatic API )您只需要使用
refs
找到元素“#exampleModal”,然后使用引导方法( Bootstrap Programmatic API )打开模态
<div id="app">
<div class="container">
<button class="btn btn-info" @click="showModal">show modal</button>
<example-modal ref="modal"></example-modal>
</div>
</div>
methods: {
showModal() {
let element = this.$refs.modal.$el
$(element).modal('show')
}
}
Without jQuery you could create a function on "method:" block like this:如果没有 jQuery,您可以在“method:”块上创建一个函数,如下所示:
openEditModal(data){
// <handle with your data>
this.$root.$emit("bv::show::modal", "your-modal-id");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.