<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue'
// 倒计时时长(秒)
const COUNTDOWN_TIME = 60
// 响应式数据
const countdown = ref(0)
const timer = ref(null)
// 计算属性
const isCounting = computed(() => countdown.value > 0)
const buttonText = computed(() => {
return isCounting.value ? `${countdown.value}秒后重新获取` : '获取验证码'
})
// 启动倒计时
const startCountdown = () => {
if (isCounting.value) return
countdown.value = COUNTDOWN_TIME
timer.value = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
clearInterval(timer.value)
}
}, 1000)
}
// 组件卸载时清除定时器
onUnmounted(() => {
if (timer.value) clearInterval(timer.value)
})
</script>
<template>
<el-link class="forget" :underline="false" :disabled="isCounting" @click="startCountdown">
{{ buttonText }}
</el-link>
</template>
<style lang="less" scoped>
.forget {
font-size: 12px;
}
</style>
目录