Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to add "close modal" button in Vue

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?

like image 491
twharmon Avatar asked Mar 10 '23 20:03

twharmon


1 Answers

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

like image 54
peaceman Avatar answered Mar 19 '23 15:03

peaceman