Ben Lin
2024-06-18 ebbd788fbb2c0b45d4473798efc57eec8ba74a25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<template>
  <Button v-bind="$attrs" :disabled="isStart" @click="handleStart" :loading="loading">
    {{ getButtonText }}
  </Button>
</template>
<script lang="ts" setup>
  import { ref, watchEffect, computed, unref } from 'vue';
  import { Button } from 'ant-design-vue';
  import { useCountdown } from './useCountdown';
  import { isFunction } from '@/utils/is';
  import { useI18n } from '@/hooks/web/useI18n';
 
  defineOptions({ name: 'CountButton' });
 
  const props = defineProps({
    value: { type: [Object, Number, String, Array] },
    count: { type: Number, default: 60 },
    beforeStartFunc: {
      type: Function as PropType<() => Promise<boolean>>,
      default: null,
    },
  });
 
  const { t } = useI18n();
  const loading = ref(false);
  const { currentCount, isStart, start, reset } = useCountdown(props.count);
 
  const getButtonText = computed(() => {
    return !unref(isStart)
      ? t('component.countdown.normalText')
      : t('component.countdown.sendText', [unref(currentCount)]);
  });
 
  watchEffect(() => {
    props.value === undefined && reset();
  });
 
  /**
   * @description: Judge whether there is an external function before execution, and decide whether to start after execution
   */
  async function handleStart() {
    const { beforeStartFunc } = props;
    if (beforeStartFunc && isFunction(beforeStartFunc)) {
      loading.value = true;
      try {
        const canStart = await beforeStartFunc();
        canStart && start();
      } finally {
        loading.value = false;
      }
    } else {
      start();
    }
  }
</script>