How to create a modal dialog in Vue.js?

To create a modal dialog in Vue.js, you can follow these steps:

  1. Create a new Vue component for the modal dialog. This component will contain the HTML markup and logic for the modal.
<template> <div class="modal" v-if="show"> <div class="modal-content"> <!-- Modal HTML markup here --> </div> </div> </template> <script> export default { props: { show: { type: Boolean, required: true } } } </script> <style> .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; } .modal-content { background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); } </style>
  1. In the parent component, create a data property to control the visibility of the modal dialog.
<template> <div> <button @click="showModal = true">Open Modal</button> <modal-dialog :show="showModal"></modal-dialog> </div> </template> <script> import ModalDialog from './ModalDialog.vue' export default { components: { ModalDialog }, data() { return { showModal: false } } } </script>
  1. Style the modal using CSS. The example above shows a simple modal with a dark semi-transparent overlay and a white content box.

  2. Now, when the "Open Modal" button is clicked, it toggles the showModal data property, which controls the visibility of the modal dialog component.