BeginnerCoder
intermediate#vue.js#modal#reusable component

Creating a Reusable Modal Component in Vue.js

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to create a reusable modal component in Vue.js that can be used throughout your application.

Introduction to Vue.js Modal Component

In this tutorial, we will create a reusable modal component in Vue.js. This component can be used to display important information to the user or to prompt the user for input.

Step 1: Creating the Modal Component

First, we need to create a new component for our modal. We can do this by creating a new file called Modal.vue in the src/components directory:

// src/components/Modal.vue
<template>
  <div v-if='isOpen' class='modal'>
    <div class='modal-content'>
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    isOpen: {
      type: Boolean,
      required: true
    }
  }
}
</script>

Step 2: Using the Modal Component

Now, we can use our modal component in our application. We can do this by importing the Modal component and using it in our template:

// src/App.vue
<template>
  <div>
    <button @click='isOpen = true'>Open Modal</button>
    <Modal :is-open='isOpen'>
      <p>This is a modal!</p>
    </Modal>
  </div>
</template>

<script>
import Modal from './components/Modal.vue'

export default {
  components: { Modal },
  data() {
    return {
      isOpen: false
    }
  }
}
</script>

Step 3: Adding a Close Button

Finally, we can add a close button to our modal. We can do this by adding a new button element to our Modal component:

// src/components/Modal.vue
<template>
  <div v-if='isOpen' class='modal'>
    <div class='modal-content'>
      <slot></slot>
      <button @click='$emit("close")'>Close</button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    isOpen: {
      type: Boolean,
      required: true
    }
  }
}
</script>
Keep going with vue.js

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.