Skip to content
Button·Free

Async button (Vue)

A Vue 3 button that runs an async action. While it waits it shows a spinner and ignores extra taps. It emits done or error, so you decide what to show next. Written in TypeScript with no libraries.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

AsyncButton.vue · 108 lines
<!--
  A button for Vue 3 that runs an async action and blocks double taps while it waits.
  While `action` runs it shows a spinner and `pendingLabel`, sets aria-busy and ignores new
  clicks. If the promise rejects, the button comes back and emits `error`.

    <AsyncButton :action="save" pending-label="Saving…" @error="showError">Save</AsyncButton>

  Colours: --button-bg and --button-text (white text on near-black by default).
-->
<script setup lang="ts">
import { ref } from 'vue';

const props = withDefaults(
  defineProps<{
    action: () => Promise<unknown>;
    pendingLabel?: string;
    disabled?: boolean;
  }>(),
  { pendingLabel: 'Working…', disabled: false },
);

const emit = defineEmits<{ done: []; error: [reason: unknown] }>();

const running = ref(false);

async function run() {
  if (running.value || props.disabled) return;
  running.value = true;
  try {
    await props.action();
    emit('done');
  } catch (reason) {
    emit('error', reason);
  } finally {
    running.value = false;
  }
}
</script>

<template>
  <button
    type="button"
    class="async-button"
    :disabled="disabled"
    :aria-disabled="running || undefined"
    :aria-busy="running || undefined"
    @click="run"
  >
    <span v-if="running" class="spinner" aria-hidden="true"></span>
    <span>
      <template v-if="running">{{ pendingLabel }}</template>
      <slot v-else>Continue</slot>
    </span>
  </button>
</template>

<style scoped>
.async-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  min-height: 44px;
  min-width: 44px;
  padding: 0.55rem 1.1rem;
  font: 600 1rem system-ui, sans-serif;
  color: var(--button-text, #ffffff);
  background: var(--button-bg, #1d1f23);
  border: 0;
  border-radius: 8px;
  cursor: pointer;
}

.async-button[aria-busy='true'] {
  cursor: progress;
}

.async-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;

This preview is shortened. You get the full content when you install it.

Changes in 1.0.0

First version.

Related