草庐IT

vue3发送验证码倒计时 (防止连点、封装复用)

奥特曼 2023-04-03 原文

一、实现思路

倒计时 流程图

二、实现一个简单的验证码倒计时

//倒计时初始变量
const codeNum = ref(60);
// 定时器id
let clearId: number;
// 发送验证码
const sendCode = async () => {
// 防止下次点击 如果倒计时的时间不是60 就不执行下面逻辑
  if (codeNum.value != 60) return;
  // 掉接口
  const res = await getCode(mobile.value, "login");
// 把定时器赋值给 变量clearId 目的:清除定时器
  clearId= setInterval(() => {
    // 每次 时间1s -1
    codeNum.value--;
    // 时间=0时 清除定时器 
    if (codeNum.value == 0) {
      clearInterval(clearId);
    // 还原 倒计时60s
      codeNum.value = 60;
    }
  }, 1000);
};

当然 这只是没有做过优化的一个发送验证码,如果要考虑点击连续点击或者离开页面时销毁定时器 还要加一些功能

三、优化 

(1)第一种方案,定义一个变量来控制 如果之前没有点击 再次点击不再执行

<script lang="ts" setup>
// 接口
import { getCode } from "@/api/login";
// 定时器id
let clearId:number;
// 倒计时时间
const codeNum = ref(60);
// 手机号
const mobile = ref("13230000001");
// 是否发送了验证码 防止连点
+ const isClickSend = ref(false);

// 发送验证码
const sendCode = async () => {
+ if (isClickSend.value || codeNum.value != 60) return;
  isClickSend.value = true;
  const res = await getCode(mobile.value, "login");
  clearId.value = setInterval(() => {
    codeNum.value--;
    if (codeNum.value == 0) {
      clearInterval(clearId.value);
      codeNum.value = 60;
+      isClickSend.value = false;
    }
  }, 1000);
  console.log("sendCode", res);
};

</script>

<template>
     <a
    href="javascript:;"
    @click="sendCode"
   >{{ codeNum == 60 ? "发送验证码" : `(${codeNum})发送验证码` }}</a>
</template>

(2)第二种方案. 让倒计时初始值为0 调用函数时在赋值为60 下次值大于0时同样不再执行,实现思路和第一种相似

const codeNum = ref(0);

const sendCode = async () => {
  if (codeNum.value > 0) return;
  isClickSend.value = true;
  const res = await getCode(mobile.value, "login");
  codeNum.value = 60 
  if(clearId) clearInterval(clearId)
  clearId = setInterval(() => {
    codeNum.value--;
    if (codeNum.value == 0) {
      clearInterval(clearId);
    }
  }, 1000);
};

其中没有对手机号进行校验 若需要则自己可以写校验规则,也可以参考当前使用的其他组件库使用 

离开页面销毁定时器

 onMounted(() => {
        clearInterval(clearId)
 })

四、逻辑封装

为什么要封装 验证码倒计时功能?

1. 为了下次再次使用时 直接copy代码达到复用

2. 在日常开发中可能 有很多场景都需要发送验证码 只是 接口一样 只是参数的type值不一样 例如 登录需要传login  注册需要传register 到时候只需要调用更换参数即可

新建composable/index.ts 准备放公共方法

// 引用 发送的验证码类型
import type { CodeType } from '@/type/user'
// 引入接口
import { getCode } from "@/api/login";
import type { Ref } from 'vue'
// 引入vant form类型 用来初始化form类型 可参考vant 若没有使用 则删除
import type { FormProps, FormInstance } from 'vant';

// 封装方法   只需要传入手机号、 type类型
export const useSendCode = (mobile:  Ref<string>, type: CodeType) => {
    // 定义定时器初始值为0
    const timer = ref(0)
    // 定义form变量 如果用了vant 记得要给vanForm 绑定ref
    const form =  ref<FormInstance | null>() ;
    // 定义定时器id 为了清除定时器
    let timerId: number
    // 之后页面调用send方法来使用 
    const send = async () => {
        // 第二次点击 大于0时 直接 return
        if (timer.value > 0) return
        // 校验 mobile字段 要和 van-field 中的name保持一直 否则校验失败 如果校验失败则不走下面代码  注意await
        await form.value?.validate('mobile')
        // 校验通过调用接口
        await getCode(mobile.value, type)
        // 赋值倒计时  可修改成自己需要的时间
        timer.value = 10
        // 如果之前id存在可清除
        if (timerId) clearInterval(timerId)
        // 赋值定时器id
        timerId = setInterval(() => {
            // 时间-1
            timer.value--
            // 倒计时结束 清除定时器
            if (timer.value == 0)  clearInterval(timerId)
            
        }, 1000)
    }
    // 
    onMounted(() => {
        clearInterval(timerId)
    })
    return { timer, send, form }
}

 由于代码中使用了插件 没有引入ref onMounted  需要可自行引入

页面中使用

<script lang="ts" setup>
    import { mobileRule } from "@/utils/rule";
    import { useSendCode } from "@/composable";
    const { send, timer, form } = useSendCode(mobile, "login");
</script> 

<template>
   <van-form ref="form" @submit="pwdLogin">
        <van-field
          v-model="mobile"
          name="mobile"
          maxlength="11"
          placeholder="请输入手机号"
          :rules="mobileRule"
        />
  </van-form>
 ...
  <a href="javascript:;" @click="sendCode" >
     {{ timer == 0 ? "发送验证码" : `(${timer})后发送验证码` }}
  </a> 
</template>

补充 mobileRule

import type { FieldRule } from 'vant'

const mobileRules: FieldRule[] = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
]

const passwordRules: FieldRule[] = [
  { required: true, message: '请输入密码' },
  { pattern: /^\w{8,24}$/, message: '密码需8-24个字符' }
]

const codeRules: FieldRule[] = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '验证码为6位数字' }
]

export { mobileRules, passwordRules, codeRules }

 

有关vue3发送验证码倒计时 (防止连点、封装复用)的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  6. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  7. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  8. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  9. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  10. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

随机推荐