如果你还不了解什么是“组合式函数”,请移步官方文档:
https://cn.vuejs.org/guide/reusability/composables.html
下面的代码块就是完整的验证码倒计时组合式函数的代码,可以直接拿来用在自己的项目中。
// utils/countDown.ts
import { ref, onUnmounted, computed } from 'vue'
import { dayjs } from 'element-plus' // 此处根据项目实际情况导入相应的依赖包
// import * as dayjs from 'dayjs'
/**
* 倒计时
* @returns
*/
export function useCountDown() {
const showLog = ref(false)
const countDownTimer = ref<any>(null)
const countDownLimit = ref<number>(60)
const countDownTextDefault = ref('获取验证码')
const countDownWorking = ref(false)
const startTime = ref<string>('')
const endTime = ref<string>('')
const startCountDown = () => {
if (countDownTimer.value && countDownWorking.value) {
if (showLog.value) {
console.error('不允许重复启动倒计时!!!')
}
return
}
startTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
countDownWorking.value = true
countDownTimer.value = setInterval(() => {
if (showLog.value) {
console.log(`IntervalTimer: ${countDownTimer.value}, CurrentCountDownValue: ${countDownLimit.value}`)
}
countDownLimit.value--
if (!countDownLimit.value) {
resetCountDown()
}
}, 1000)
}
const resetCountDown = () => {
if (countDownTimer.value) {
clearInterval(countDownTimer.value)
countDownTimer.value = null
countDownLimit.value = 60
countDownWorking.value = false
endTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
const costTime = dayjs(endTime.value).diff(dayjs(startTime.value), 'second')
if (showLog.value) {
console.log(`倒计时耗时:${costTime}秒`)
}
}
}
const countDownText = computed(() => {
return countDownWorking.value ? `${countDownLimit.value} 秒后重新获取` : countDownTextDefault.value
})
onUnmounted(() => {
resetCountDown()
})
return { countDownTimer, countDownLimit, countDownTextDefault, countDownText, countDownWorking, startCountDown, resetCountDown, showLog }
}
这样就在你的项目中创建了一个组合式函数(文件),下面应用部分介绍具体如何使用。
代码结构很简单,无非就是一些状态和方法,对外暴露的属性可以在调用时对组合式函数进行配置,对外暴露的方法可以进行功能交互控制。下面具体说明:
【暴露的属性】
【暴露的方法】
# 安装
npm install dayjs
yarn add dayjs
pnpm add dayjs
# 引入
import * as dayjs from 'dayjs'
下面的示例代码基于element-plus构建,自己可以根据实际情况进行调整。
<!-- 本示例代码基于element-plus构建 -->
<template>
<el-button
type="primary"
@click="onGetCodeClick"
style="width: 100%"
:disabled="countDownWorking">
{{ countDownText }}
</el-button>
</template>
<script setup lang="ts">
import { useCountDown } from '/@/utils/countDown'
const { startCountDown, countDownText, countDownWorking, showLog } = useCountDown()
showLog.value = true // 打开浏览器控制台显示运行日志
const onGetCodeClick = () => {
// 此处可以添加自己的业务逻辑,比如检查手机号或者邮箱是否已正确输入,不正确则不触发倒计时
startCountDown()
}
</script>
后续我会分享一个完整的手机验证码登录案例来演示本文的组合式函数的实际应用。
🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。