按钮·免费
异步按钮(Vue)
一个 Vue 3 按钮,执行异步操作,等待时显示加载动画,完成前忽略多余的点按。它会发出 done 或 error 事件,接下来显示什么由你决定。TypeScript,无需任何库。
免费安装。
如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。
预览
AsyncButton.vue · 108 行
<!--
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;此预览已截短。安装后可获得完整内容。
1.0.0 的变更
首个版本。