新项目选用了vue3,正好写到短信验证码倒计时这种常见功能,就借鉴vue3新组合API的方式封装一下这类功能。废话不多说,直接上代码
创建一个单独的文件
//getcode/index.js
import {ref, computed, onUnmounted } from "vue";
import {isValidPhoneNum} from "@/common/utils";
/**
* @param config {
* countDown 倒计时时间 秒 非必传 默认60s
* codeRequest(){ 获取验证码的接口逻辑 回调 }
* fail(params) { 手机号错误处理 } 非必传
* }
* @returns
* countDown 倒计时秒数
* send 触发函数
* disabled 是否可用 能否重新获取
* btnText 点击按钮文字
*/
const getCode = (config) => {
const isTriggered = ref(false);
const countDown = ref(0);
let timer=null;
const disabled = computed(()=>countDown.value > 0);
const btnText = computed(()=>{
if(disabled.value) return `${countDown.value}s`;
if(isTriggered.value) return "重新获取";
return "获取验证码";
})
const send = async (phone)=>{
if(disabled.value) return;
if(!isValidPhoneNum(phone)){
console.error('手机号错误');
if(config.fail){
config.fail("手机号错误");
}
return;
}
await config.codeRequest(phone);
isTriggered.value = true;
countDown.value = config.countDown || 60;
if(timer)clearInterval(timer);
timer=setInterval(()=>{
countDown.value--;
if(countDown.value === 0) clearInterval(timer);
},1000)
}
onUnmounted(()=>{
clearInterval(timer)
})
return { countDown, send, btnText}
}
export default getCode;
用到@/common/utils里的方法 isValidPhoneNum
export const isValidPhoneNum = (str)=>{
var reg_tel = /^(1[3-9][0-9])\d{8}$/;
if (reg_tel.test(str)) {
return true;
}
return false;
}
如何调用
<template>
<van-field
class="vaninput"
v-model="sms"
center
clearable
placeholder="请输入短信验证码"
>
<template #button>
<span class="msgbtn" @click="getSms">{{btnText}}</span>
</template>
</van-field>
</template>
<script setup>
import { ref } from 'vue';
import getCode from '@/common/getcode';
const sms = ref('');
const { send, btnText } = getCode({
codeRequest: async (phone)=>{
//await 发送验证码接口逻辑
console.log('接口调用')
}
})
// 获取验证码
const getSms = () =>{
send('13500000000')
}
</script>
- THE END -
最后修改:2024年10月24日