lab002: Modals in Vue
July 22, 2022
Click on the button below to see a basic modal I created.
When “show modal” is clicked, an event listener runs toggles a boolean flag to true. The modal has a “v-if” directive listening to the flag, managaing the state of the modal accordingly. In this case it’s simply true or flase, not visible or showing.
Now that the modal is showing, we can see that CSS does a lot of the heavy lifting. The graying out the entire background behind the modal card? CSS. Positioning the modal card and making everything look good, including the hover effect on the buttons? CSS.
Features
You may have noticed that you can close the modal in two ways.
- You can click the x icon in the upper right. An event listener on this icon toggles the showModal boolean flag to false.
- You can click anywhere outside the modal card. This was easily implemented by using vueUse’s onClickOutside composable function. Wire up a template ref to your target, and onClickOutside will take care of the rest–clicking anywhere other than your target will run your callback code.
This modal component provides flexibility through its props. Check out the configuration below, which powers the modal above.
<template>
<Modal
v-if="isModalShowing"
title="Your modal title here"
content="What do you want to say? Let it all out here."
text-left
has-button1
button1-text="Your button #1"
has-button2
button2-text="Your button #2"
@close-modal="closeModal"
/>
</template>
<template>
<Modal
v-if="isModalShowing"
title="Your modal title here"
content="What do you want to say? Let it all out here."
text-left
has-button1
button1-text="Your button #1"
has-button2
button2-text="Your button #2"
@close-modal="closeModal"
/>
</template>
Summary
Creating a customizable, reusable modal component in Vue 3 is really easy. You might find that making your own saves you time in the long run!
You can view the Modal.vue source code here. Note that I’m using Unocss with Attributify so my Tailwind classes might look a little funky.