Search code examples
javascriptvue.jsvuejs2uikit

UIkit modal element is not removed from DOM when parent component is destroyed (Vue.js)


I'm using UIKit modal on my Vue app.

UIkit.modal(element).show(); // adds class uk-open and style="display:block"
UIkit.modal(element).hide(); 

Hide just removes class uk-open and style="display:block". I noticed that even after the parent component of modal is destroyed, the modal element remains on the DOM. I've also noticed that on show, the element modal is moved at the very bottom of body just before the end body tag. On first load it would be at where it is declared within the component. (Could that be the reason why it wasn't seen and therefore not removed?) Problem occurs when I move to different component and the go back to open the component with the modal as child component and trigger show again. The modal elements on the DOM pile up and are not removed.

One workaround I've tried is instead of a button triggering the show, I added a condition and if that returns true, the element will be added to the DOM and trigger show.

    <field-form-modal
        v-if="showModal"
        .....
    />

    watch: {
    showModal(show) {
        if (show) {
            UIkit.modal('#field-form-modal').show();
        }
    }
},

However, by the time I reach this line: UIkit.modal('#form-field-modal').show(); . The element is not yet on the DOM. Thus, I get this error: Cannot read property 'show' of undefined. If my assumption is correct, I think it will only be added after showModal watch function.

Any suggestions on how to fix this? Thank you!


Solution

  • Parent component id should be set as container in modal

    // Parent component
    <div id="parent-component">
        
      <sample-modal/>
    </div>
    
    
    // Modal component
    <div
        id="sample-modal"
        class="uk-modal"
        container="#parent-component"
    >
         // contents
    </div>