效果图:
<span @click="send">{{ time === 0 ? '发送验证码' : `${time}秒后发送` }}</span>
<script setup>
import { ref } from 'vue'
import { userMobileLoginMsg } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否立即开启)
const time = ref(0)
const { pause, resume } = useIntervalFn(() => {
time.value--
if (time.value <= 0) {
pause()
}
}, 1000, false)
// 发送短信
// 1. 发送验证码
// 1.1 绑定发送验证码按钮点击事件
// 1.2 校验手机号,如果成功才去发送短信(定义API),请求成功开启60s的倒计时,不能再次点击,倒计时结束恢复
// 1.3 如果失败,失败的校验样式显示出来
const send = async () => {
// 没有倒计时才可以发送请求
if (time.value === 0) {
// 发送ajax请求 form.mobile是填写的手机号
await userMobileLoginMsg(form.mobile)
time.value = 60
resume()
} else {
// 失败 提示错误信息
}
}
</script>