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);
};

你可能感兴趣的:(vue.js,缓存,前端)