2π
As already mentionned, I would have use slots and dynamic component rendering to accomplish what youβre trying to do in a cleaner way.
See snippet below (I didnβt make them modals as such but the idea is the same).
This way, you can have a generic modal
component that deals with the shared logic or styles and as many modalContent
sub-components as needed that are injected via the dedicated slot.
Vue.component('modal', {
template: `
<div>
<h1>Shared elements between modals go here</h1>
<slot name="content"/>
</div>
`
});
Vue.component('modalA', {
template: `
<div>
<h1>I am modal A</h1>
</div>
`
});
Vue.component('modalB', {
template: `
<div>
<h1>I am modal B</h1>
</div>
`
});
Vue.component('modalC', {
template: `
<div>
<h1>I am modal C</h1>
</div>
`
});
new Vue({
el: "#app",
data: {
modals: ['modalA', 'modalB', 'modalC'],
activeModal: null,
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-for="modal in modals" @click="activeModal = modal"> Open {{ modal }} </button>
<modal>
<template slot="content">
<component :is="activeModal"></component>
</template>
</modal>
</div>
1π
Update
Now, You might think how will you close your modal and let the parent component know about it.
On click of button trigger closeModal
for that
Create a method β closeModal
and inside commonModal component and emit
an event.
closeModal() {
this.$emit('close-modal')
}
Now this will emit a custom event which can be listen by the consuming component.
So in you parent component just use this custom event like following and close your modal
<main class="foo">
<commonModal v-show="isVisible" :data="data" @close- modal="isVisible = false"/>
<!-- Your further code -->
</main>
So as per your question
A β How do I reuse the modal dialog, instead of creating 3 separate dialogs
Make a separate modal
component, let say β commonModal.vue
.
Now in your commonModal.vue
, accept single prop
, let say data: {}
.
Now in the html
section of commonModal
<div class="modal">
<!-- Use your received data here which get received from parent -->
<your modal code />
</div>
Now import the commonModal
to the consuming/parent component. Create data property in the parent component, let say β isVisible: false
and a computed property for the data
you want to show in modal
let say modalContent
.
Now use it like this
<main class="foo">
<commonModal v-show="isVisible" :data="data" />
<!-- Your further code -->
</main>
The above will help you re-use modal and you just need to send the data
from parent component.
Now second question will also get solved here How do I know which modal dialog has been triggered?
Just verify isVisible
property to check if modal
is open or not. If isVisible = false
then your modal is not visible and vice-versa