- read

How to Create a Modal Popup in Vue.js

John Philip 14

Screenshot by Author from https://www.nngroup.com/

Introduction

Modals are very common in most modern applications. They primarily serve to present concise information and are well-suited for displaying ads and promotional content. Modals offer a swift means of conveying information, with user-friendly dismissal options.

In this article, we are going to build a popup modal in Vuejs. The modal will include a cancel or close button for user convenience, allowing them to dismiss it after completing their task. Additionally, we’ll implement a feature that enables users to click outside the active modal area to dismiss it.

Modal popup component

<script setup lang="ts">
import { ref } from 'vue';

const message = ref('This is a modal popup');
const emit = defineEmits(['close']);

const closeModal = () => {
emit('close');
};
</script>
<template>
<div class="popup" @click.self="closeModal">
<div class="popup-content">
<div class="popup-header">
<h2 class="popup-title">{{ message }}</h2>
<button class="popup-close-button" @click.prevent="closeModal">X</button>
</div>
<article>
<div class="popup-content-text">
This is a simple modal popup in Vue.js
</div>
</article>
</div>
</div>
</template>

Script Section:

<script setup lang="ts">
import { ref } from 'vue';
const message = ref('This is a modal popup');
const emit = defineEmits(['close']);
const closeModal = () => {
emit('close');
};
</script>

In this section, we import the necessary functionality from Vue.

  • ref is used to create a reactive variable message that contains the message displayed in the modal.
  • emit is used to define an event named “close” that can be emitted to close the modal.
  • closeModal is a function that emits the “close” event when called, effectively closing the modal.

Template Section:

<template>
<div class="popup" @click.self="closeModal">
<div class="popup-content">
<div class="popup-header">
<h2 class="popup-title">{{…