useCountDown:计时器Hook
常见使用场景:验证码发送完之后的读秒
import { ref } from 'vue'
export function useCountDown() {
const countNum = ref(0)
const countInterval = ref(null)
const startCountDown = num => {
countNum.value = Number(num)
clearCountDown()
countInterval.value = setInterval(() => {
if (countNum.value === 0) {
clearInterval(countInterval.value)
countInterval.value = null
return
}
countNum.value--
}, 1000)
}
const clearCountDown = () => {
if (countInterval.value) {
clearInterval(countInterval.value)
}
}
return { countNum, startCountDown, clearCountDown }
}
useDebounce:防抖函数封装
常见使用场景:输入框搜索、输入框校验等场景。
import { ref } from 'vue'
export function useDebounce(cb, delay = 150) {
const timer = ref(null)
const handler = () => {
if (timer.value) {
clearTimeout(timer.value)
timer.value = setTimeout(() => {
cb()
}, delay)
} else {
timer.value = setTimeout(() => {
cb()
}, delay)
}
}
return handler
}
Comments