| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- // hooks/useEmailCountdown.ts
- import { ref, computed, onUnmounted } from 'vue'
- import { useI18n } from 'vue-i18n'
- import ls from "@/utils/store2";
- interface UseEmailCountdownOptions {
- duration?: number
- storageKey?: string
- }
- export function useEmailCountdown(options: UseEmailCountdownOptions) {
- const { t } = useI18n()
- const {
- duration = 60,
- storageKey = 'email_countdown'
- } = options || {}
- const time = ref<number>(duration)
- const endTime = ref<number>(0)
- let timer: ReturnType<typeof setInterval> | null = null
- const text = computed(() => {
- if (time.value === duration) {
- return t('newSignup.item11')
- }
- return `${t('signup.form.waitCode1')}${time.value}${t('signup.form.waitCode2')}`
- })
- const canSend = computed(() => time.value === duration)
- const tick = () => {
- const remain = Math.floor((endTime.value - Date.now()) / 1000)
- time.value = remain > 0 ? remain : duration;
- if (time.value === duration) {
- clear()
- }
- }
- const start = () => {
- clear()
- endTime.value = Date.now() + duration * 1000
- ls.set(storageKey, String(endTime.value))
- tick()
- timer = setInterval(tick, 1000)
- }
- const restore = () => {
- const saved = Number(ls.get(storageKey))
- if (!saved) return
- if (saved > Date.now()) {
- endTime.value = saved
- tick()
- timer = setInterval(tick, 1000)
- }
- }
- const clear = () => {
- if (timer) {
- clearInterval(timer)
- timer = null
- // time.value = duration
- }
- ls.set(storageKey, '')
- }
- onUnmounted(clear)
- return {
- time,
- text,
- canSend,
- start,
- restore,
- clear
- }
- }
|