80 lines
2.0 KiB
Vue
80 lines
2.0 KiB
Vue
<script setup lang="ts">
|
|
import { computed, onBeforeUnmount, ref } from "vue";
|
|
import {
|
|
Button,
|
|
Description,
|
|
FieldError,
|
|
Form,
|
|
Label,
|
|
NumberField,
|
|
NumberFieldGroup,
|
|
NumberFieldInput,
|
|
NumberFieldIncrementButton,
|
|
NumberFieldDecrementButton,
|
|
Spinner,
|
|
} from "@heroui-vue/components";
|
|
const value = ref<number | null>(null),
|
|
isSubmitting = ref(false);
|
|
const STOCK_AVAILABLE = 3;
|
|
const isOutOfStock = computed(
|
|
() => value.value !== null && value.value > STOCK_AVAILABLE,
|
|
);
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
function submit() {
|
|
if (
|
|
isSubmitting.value ||
|
|
value.value === null ||
|
|
value.value < 1 ||
|
|
value.value > STOCK_AVAILABLE
|
|
)
|
|
return;
|
|
const submittedValue = value.value;
|
|
isSubmitting.value = true;
|
|
// Simulate API call
|
|
timer = setTimeout(() => {
|
|
console.log("Order submitted:", { quantity: submittedValue });
|
|
value.value = null;
|
|
isSubmitting.value = false;
|
|
}, 1500);
|
|
}
|
|
onBeforeUnmount(() => {
|
|
if (timer !== undefined) clearTimeout(timer);
|
|
});
|
|
</script>
|
|
<template>
|
|
<Form class="flex w-[280px] flex-col gap-4" @submit.prevent="submit">
|
|
<NumberField
|
|
v-model="value"
|
|
is-required
|
|
:is-invalid="isOutOfStock"
|
|
:max-value="5"
|
|
:min-value="1"
|
|
name="quantity"
|
|
>
|
|
<Label>订购数量</Label>
|
|
<NumberFieldGroup>
|
|
<NumberFieldDecrementButton />
|
|
<NumberFieldInput class="w-[120px]" />
|
|
<NumberFieldIncrementButton />
|
|
</NumberFieldGroup>
|
|
<FieldError v-if="isOutOfStock">
|
|
仅剩 {{ STOCK_AVAILABLE }} 件库存
|
|
</FieldError>
|
|
<Description v-else>仅剩 {{ STOCK_AVAILABLE }} 件可购</Description>
|
|
</NumberField>
|
|
<Button
|
|
class="w-full"
|
|
:is-disabled="value === null || value < 1 || value > STOCK_AVAILABLE"
|
|
:is-pending="isSubmitting"
|
|
type="submit"
|
|
variant="primary"
|
|
>
|
|
<template v-if="isSubmitting">
|
|
<Spinner color="current" size="sm" />
|
|
处理中…
|
|
</template>
|
|
<template v-else>下单</template>
|
|
</Button>
|
|
</Form>
|
|
</template>
|