vue封装短信验证码,刷新缓存倒计时

HTML代码

          <a-form-item field="verifyCode" label="验证码:">
            <a-input v-model="formData.verifyCode" placeholder="短信验证码" class="login-form-button" allow-clear>
              <template #append>
                <span
                  :class="{ 'login-form-send': true, 'login-form-send-disabed': typeof theTime == 'number' }"
                  @click="sendVerificationCode"
                  >{{ theTime }}{{ theTime != '发送验证码' ? 's' : '' }}</span
                >
              </template>
            </a-input>
          </a-form-item>

ts部分

import { VueCookieNext } from 'vue-cookie-next'; //存储秒数的插件,可用localStorage代替,存储秒数加上时间戳
const base = reactive<any>({
	theTime: '发送验证码'// 发送验证码/倒计时
})

// 进页面就执行的方法
const init = () => {
	const timeA: any = 'timeA';
	// 如果存储的有时间,theTime赋值为秒
  if (VueCookieNext.isCookieAvailable(timeA)) {
    const timeB = loctionTime();
    base.theTime = Math.trunc(Number(VueCookieNext.getCookie(timeA)) - timeB);
    setIntervalFunction();
  }
}

/**
 * @function sendVerificationCode
 * @description 发送验证码
 */
const sendVerificationCode = () => {
  if (typeof base.theTime == 'number') {
    // 已经有倒计时不允许点击
    return;
  }
  // 校验手机号码是否有输入
  base.phoneRef.validateField('mobilePhone', (valid: any) => {
    if (valid == void 0) {
      const param = {
        mobilePhone: base.formData.mobilePhone,
        type: 'REGISTER',
      };
      sendVerifyCode(param).then((res: any) => {
        if (res.code == 200) {
          base.theTime = 60;
          const locTime = loctionTime();
          const CodeData: any = locTime + 60;
          VueCookieNext.setCookie('timeA', CodeData, { expire: '60s' });
          setIntervalFunction();

          Message.success(res.message || '发送成功,请去手机查看!');
        } else {
          Message.error(res.message || '发送失败');
        }
      });
    }
  });
};

/**
 * @setIntervalFunction 计时器方法
 */
const setIntervalFunction = () => {
  const theBottom = setInterval(() => {
    if (base.theTime > 0) {
      base.theTime--;
    } else if (base.theTime == 0) {
      base.theTime = '发送验证码';
      clearInterval(theBottom);
    }
  }, 1050);
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值