Hi, that was probably the longest title I’ve ever written before. But it was necessary—there’s no clean way of summarizing the task.

In modern web development we make a lot of use of modals for alerting users and confirming actions. And of course, no one likes using the alert and confirm functions the browser APIs give us in JavaScript—browser default modals look horrible. But there’s one thing about those functions that intrigued me: they can stop script execution until they receive a user response. I wanted something similar—a way to await the user response from my own alertConfirm modal.

The reason for doing this could be that you don’t want to leave your current function, and you wish to perform certain actions based on the user response inside that function. The best use case I encountered was inside a beforeLeave route guard: I didn’t want to leave the route if the user clicked “No” in my alertConfirm modal.

Originally published on Medium.

TypeScript openAlertConfirm function that awaits alertConfirm.value.openModal with an alert or confirm message
Calling openModal from a parent component and awaiting the boolean result.

The above image is an example of how this modal component will be used inside a view or any other component. The first parameter the function takes is the message you wish to display inside the modal. The second parameter is a Boolean—if true, the modal will be an alert and will have only one button.

UI Screenshots from the project

Dark-themed alert modal with a single Okay button and a checkmark icon
Alert mode: one Okay button.
Dark-themed confirm modal with Yes and No buttons
Confirm mode: Yes and No buttons.

Project link: akshat-triv/Custom-Vue-Alert-Confirm-Modal.

I’m using Vite and TypeScript in my project, but that shouldn’t affect you even if you don’t know TypeScript—you can ignore the types.

Creating the AlertConfirm modal component

I’m using the Composition API and <script setup> way of writing Vue SFCs. In the setup I’ve imported my button component, along with the icon components I want inside my buttons. I’ve also imported ref and computed from Vue.

Refs, variables, and computed properties

  1. showConfirm — makes the modal visible when the value is true.
  2. modalType — can only be "confirm" or "alert". If the value is "confirm", the modal has two buttons with the text “Yes” and “No”. If the value is "alert", the modal has only one button with the text “Okay”.
  3. alertConfirmMessage — stores and displays the message text inside the modal.
  4. trueBtnText — a computed property for the button that returns true; the label changes based on modalType.
  5. falseBtnText — a ref for the text on the button that returns false when clicked.
  6. resolvePromise — a let variable that later stores the resolve function’s reference. Don’t worry too much about this now—you’ll see why it matters. Its type is a function that takes a boolean (or PromiseLike<boolean>) and returns void.

Here’s the component (AlertConfirm.vue in the article; the companion repo names the file AlertConfirmModal.vue):

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

import CommonButton from '@/components/CommonButton.vue'
import CheckIcon from '@/components/icons/IconCheck.vue'
import CrossIcon from '@/components/icons/IconCancel.vue'

const showConfirm = ref(false)
let resolvePromise: (value: PromiseLike<boolean> | boolean) => void

const modalType = ref<'confirm' | 'alert'>('confirm')

const alertConfirmMessage = ref<null | string>(null)
const trueBtnText = computed(() =>
  modalType.value === 'confirm' ? 'Yes' : 'Okay',
)
const falseBtnText = ref('No')

function openModal(message: string, alertModal: boolean) {
  alertConfirmMessage.value = message
  modalType.value = alertModal ? 'alert' : 'confirm'

  showConfirm.value = true

  return new Promise((resolve) => {
    resolvePromise = resolve
  })
}

function handleUserInput(value: boolean) {
  if (!resolvePromise) return

  resolvePromise(value)
  showConfirm.value = false
}

defineExpose({ openModal })
</script>

<template>
  <transition name="fade-up">
    <div
      v-if="showConfirm"
      class="alert-box"
    >
      <div class="alert-box-header">
        {{ alertConfirmMessage }}
      </div>
      <div class="alert-box-buttons">
        <common-button
          :button-text="trueBtnText"
          :primary="true"
          @click="handleUserInput(true)"
        >
          <check-icon />
        </common-button>
        <common-button
          v-if="modalType === 'confirm'"
          :button-text="falseBtnText"
          @click="handleUserInput(false)"
        >
          <cross-icon />
        </common-button>
      </div>
    </div>
  </transition>
</template>

I have two buttons inside the component: one returns true when clicked and the other returns false. The false-returning button is hidden when modalType is "alert".

openModal

This function takes two arguments: the message to display, and a Boolean—if true, we set modalType to "alert". At the start we set showConfirm to true, set alertConfirmMessage to the first argument, and update modalType from the second argument when needed.

After that we return a new Promise, and inside the executor we assign the resolve function to the resolvePromise variable declared earlier. We don’t call resolve inside this component for the open path. Instead we expose openModal with defineExpose so parent components can call it and await the user’s response. We can use await because we’re returning a Promise.

handleUserInput

When the user clicks a button inside the modal, we call this function with true or false—true for the true button, false for the false button (hidden in alert mode). Inside the function we check that resolvePromise is defined (to keep TypeScript happy), call it with the boolean we received, then set showConfirm to false to close the modal.

handleUserInput only runs when showConfirm is true, and that only happens after openModal has been called—so resolvePromise will already hold the resolve from the Promise returned by openModal.

Using AlertConfirm inside other components

Follow these steps:

  1. Import the component.
  2. Add it to your template, and bind a template ref (for example alertConfirm).
  3. When you want to open the modal:
// Alert (one button)
await alertConfirm.value?.openModal('This will be an alert', true)

// Confirm (Yes / No)
await alertConfirm.value?.openModal('This will be a confirm')

Here’s how I wired it in App.vue—two buttons, one for alert and one for confirm:

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

import CommonButton from './components/CommonButton.vue'
import AlertConfirmModal from './components/AlertConfirmModal.vue'

const alertConfirm = ref<InstanceType<typeof AlertConfirmModal> | null>(null)

async function openAlertConfirm(alertModal = false) {
  const alertMessage =
    'Hi!, You created a custom async alert modal. This was amazing.'

  const confirmMessage = 'It was quite interesting and elegant right?'

  const userInput = await alertConfirm.value?.openModal(
    alertModal ? alertMessage : confirmMessage,
    alertModal,
  )

  console.log('This was the user input', userInput)
}
</script>

<template>
  <div class="buttons-wrapper">
    <CommonButton
      button-text="Open Alert"
      :primary="true"
      @click="openAlertConfirm(true)"
    />
    <CommonButton
      button-text="Open Confirm"
      :primary="true"
      @click="openAlertConfirm(false)"
    />
  </div>
  <div class="alert-modal">
    <AlertConfirmModal ref="alertConfirm" />
  </div>
</template>

And that’s it—you have a way to write alert and confirm modals that you can await.

If you want the full project, it’s on GitHub: akshat-triv/Custom-Vue-Alert-Confirm-Modal.

Thanks for reading—see you next time.