import {useIntervalFn} from '@vueuse/core'
const {pause, resume} =useIntervalFn(() => {// 具体要做的事件}, 间隔时间, {immediate: false|true})
pause() // 暂停,进行
resume()// 持续,开始
export const useCountdown = () => {const time = ref(0)
const {pause, resume} = useIntervalFn(() => {
// 每隔多长时间做什么 回调
time.value--
if (time.value <= 0) {pause()
}
console.log('useIntervalFn', Date.now())
}, 1000, {immediate: false})
// pause: 暂停,
// resume: 开始
const start = (num) => {
time.value = num
resume()}
return {time, start}
}
const {time, start} = useCountdown()
// 发手机验证码
const send = async () => {
// 1. 验证手机号格局
if (mobile(formData.mobile) !== true) {Message({ type: 'error', text: '手机号格局不对'})
return
}
if (time.value !== 0) {return}
// 2. 调用 api
try {await userMobileLoginMsg(formData.mobile)
Message({type: 'success', text: '验证码曾经发送!'})
// 倒计时
start(60)
} catch (err) {console.dir(err)
Message({type: 'error', text: err.response.data.message})
}
}
<span @click="send()" class="code">
{{time===0?'发送验证码':`${time} 秒后发送 `}}
</span>