vue 发送验证码+倒计时组件

效果图
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

组件代码

<template>
  <el-button
    @click="getCodeFlag && getSecuntyCode()"
    :loading="getCodeLoading"
    >{{ codeText }}</el-button
  >
</template>
<script>
import { sendCode } from '@/api/user.js'
export default {
  name: 'SecurityCode',
  components: {},
  props: {
    email: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      getCodeLoading: false,
      time: 60, // 倒计时初始值
      codeText: '获取验证码',
      getCodeFlag: true
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async getSecuntyCode () {
      this.getCodeLoading = true
      this.getCodeFlag = false
      if (!this.isValid(this.email)) {
        this.getCodeLoading = false
        this.getCodeFlag = true
        return this.$message({
          message: '邮箱格式填写正确了,再获取验证码哦!',
          type: 'warning'
        })
      }
      try {
        await sendCode({ email: this.email, type: 0 })
        this.$message.success('验证码已发送!')
      } catch (error) {
        this.$message.error('获取验证码失败!')
      }
      this.getCodeLoading = false
      this.countDown()
    },
    countDown () {
      const interval = window.setInterval(() => {
        this.codeText =
          (this.time < 10 ? '0' + this.time : this.time) + '秒后重新发送'
        --this.time
        if (this.time < 0) {
          this.time = 60
          this.codeText = '重新发送'
          this.getCodeFlag = true
          window.clearInterval(interval)
        }
      }, 1000)
    },
    // 判断email的合法性
    isValid (value) {
      const phoneReg =
        /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (phoneReg.test(value)) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
<style scoped lang="less"></style>

使用步骤
引用

import SecurityCode from '@/components/security-code'

注册组件

components: {
    SecurityCode
  }

使用
要传入email(因为要校验其是否合法 再先服务器发起请求)

<security-code
            :email="createQuickForm.email"
            ></security-code
          >
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值