Reputation: 4272
This works, but I'm sure there is a much better way to do this. Please look at the document.getElementsByClassName()
part near the bottom.
html:
<modal>
<a slot="trigger">Show Modal</a>
<h3 slot="header">My Heading</h3>
<p slot="body">Here is the body of the modal.</p>
<div slot="footer">
Here is the footer, with a button to close the modal.
<button class="close-modal">Close Modal</button>
</div>
</modal>
Modal.vue:
<template>
<span>
<span @click="show = true">
<slot name="trigger"></slot>
</span>
<slot name="header"></slot>
<slot name="body"></slot>
<slot name="footer"></slot>
</span>
</template>
<script>
export default {
data() {
return { show: false }
},
mounted(that = this) {
document.getElementsByClassName('close-modal')[0].addEventListener('click', function () {
that.show = false;
})
}
}
</script>
Is there a better way to do this?
Upvotes: 4
Views: 30507
Reputation: 413
or whatever bootstrap version you have, when bootstrap opens a modal it adds 2 classes .fade .show
if you don't know what classes it adds in your BS version you can inspect an opened modal and see
then try this:
document.documentElement.querySelector(".modal.fade.show .btn-close").click();
Upvotes: 0
Reputation: 1721
Yes there is and it's to emit close event from within modal component and than handle closing in parent component when close emit is received. I can't take credit because I saw this on official vue site here.
Basically in modal template
<button @click="$emit("close")">close </button>
And then in component where you use modal add open modal property in data
data: function () { return { open: false }}
And when you use modal component
<modal @close="open = false">...</modal>
Mind @close is the event you emitted from modal it can be whatever @die works if you used $emit ("die") in modal.
And when you want to open modal you can use similar approach
<a @click="open = true">open modal</a>
If you do this its data driven and easy to reuse.
edit
Ok so if you want to add buttons from outside of modal component then define your slots and just add a button in one of those slots or all of them that will make open = false
Upvotes: 8