Background
Typically, when using modals within Vue.js components, it is the norm to create a reusable modal
component, and then control the state of this component using events from child components.
For example, consider the following code:
App.vue
<div id="app">
<!-- Main Application content here... -->
<!-- Place any modal components here... -->
<modal ref="ContactForm"></modal>
</div>
ChildComponent.Vue
To open the modal from a child component, we would simply trigger the following event:
bus.$emit('open-modal', 'ContactForm');
Note 1: bus
is a separate Vue instance that allows events to be fired between all components regardless of their relation.
Note 2: I have intentionally left out my modal
component code as it is not relevant to the question.
The Problem
Whilst the above works absolutely fine, there is one key issue...
In order to add a modal
to my application, instead of placing the modal
component within the child component that references it, I have to place all modals within App.vue
as this ensures they are as high up the DOM tree as possible (to ensure they appear above all content).
As a result, my App.vue
has the potential to end up looking like this:
<div id="app">
<!-- Main Application content here... -->
<!-- Place any modal components here... -->
<modal ref="SomeModal1"></modal>
<modal ref="SomeModal2"></modal>
<modal ref="SomeModal3"></modal>
<modal ref="SomeModal4"></modal>
<modal ref="SomeModal5"></modal>
<modal ref="SomeModal6"></modal>
<modal ref="SomeModal7"></modal>
</div>
It would be much cleaner to be able to place the modal
component within the DOM of the child component.
However, in order to ensure that the modal appears above all content within the DOM (specifically items with a set z-index
), I can't see an alternative to the above...
Can anyone suggest a way in which I can ensure my modals will work correctly, even if they are placed within the child components?
Potential Solution
I did think about the following solution but it seems very dirty...
- Fire
open-modal
event - Move the relevant
modal
component to the parentApp.vue
component - Show the modal
Additional Information
In case the above isn't clear, I am trying to avoid defining all modals in my App.vue
component, and allow defining of my modals within any child component.
The reason I am not able to do this, at present, is because the HTML for the modals must appear as high in the DOM tree as possible in order to ensure they appear above all content.